How can I read input from the console using the Scanner class in Java?

A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It's really quite simple.

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

To retrieve a username I would probably use sc.nextLine().

System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);

You could also use next(String pattern) if you want more control over the input, or just validate the username variable.

You'll find more information on their implementation in the API Documentation for java.util.Scanner


Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();

Reading Data From The Console

  • BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.

    readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n

  • Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace.

    « Until the user enters data, the scanning operation may block, waiting for input. « Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream. « A scanner however is not thread safe. It has to be externally synchronized.

    next() « Finds and returns the next complete token from this scanner. nextInt() « Scans the next token of the input as an int.

Code

String name = null;
int number;

java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);

java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next();  // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);

// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
    // Read a line from the user input. The cursor blinks after the specified input.
    name = cnsl.readLine("Name: ");
    System.out.println("Name entered: " + name);
}

Inputs and outputs of Stream

Reader Input:     Output:
Yash 777          Line1 = Yash 777
     7            Line1 = 7

Scanner Input:    Output:
Yash 777          token1 = Yash
                  token2 = 777