How to Take User Input in Java Using Scanner?

JOptionPane is one of many ways to take input from user in java. Scanner can also be used to take user input. It is a text scanner which can parse primitive types and strings using regular expressions.

input in java using Scanner

Here is the code snippet to use Scanner to take input from user:

import java.util.Scanner;

 

public class ScannerTest {

 

public static void main(String[] args) {

  Scanner s = new Scanner(System.in);

  System.out.println(“What is your name?”);

  String name = s.next();

  System.out.println(“Name: ” + name);

}

}

Output of the above code fragment would be:
What is your name?
Shailesh
Name: Shailesh

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s