The Scanner class in Java can be used to read input from the user. It provides methods to read various kinds of inputs from the user, and also detect if the input is valid.

Reading user input from the console

To read user input from the console, import the Scanner class from the java.util package and initialize a Scanner object with the value of System.in. At the end of our program, we should close the Scanner object by calling the .close() method.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // your code here
        scanner.close();
    }
}

The Scanner class provides a variety of methods to read different kinds of user input. For example, we can read a line of input as a string using the nextLine() method. An example is shown below:

Scanner scanner = new Scanner(System.in);
System.out.println("What's your name?");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();

Here's the output of the following program. We've entered "John Smith" as the user input in this example:

What's your name?
John Smith
Hello, John Smith!

Similarly, we can use nextInt() to read an integer from the user. An example is shown below:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int num1 = scanner.nextInt();
System.out.println("You entered " + num1);
scanner.close();

The output of the program is given below. We've entered 123 as the input in this case:

Enter a number:
123
You entered 123

The next() method in the Scanner class is useful when you want to read a string from the user, but only up to the nearest whitespace character (spaces, tabs or newlines, i.e. the enter key). So, for example, if you want to read in the first and last name of a user, you can do something like this:

Scanner scanner = new Scanner(System.in);

System.out.println("Type in your first name:");
String firstName = scanner.next();

System.out.println("Type in your last name:");
String lastName = scanner.next();

System.out.println("First name = " + firstName + " Last name = " + lastName);
scanner.close();

The output of the program demonstrates that firstName and lastName are stored separately:

Type in your first name:
John
Type in your last name:
Smith
First name = John, Last name = Smith

Even if all the input is typed in at once, the next() method will return each space-separated string one at a time. Here, even though we've typed "John Smith" in the same line, they are separated by spaces and so, firstName is set to "John" and lastName is set to "Smith".

Type in your first name:
John Smith
Type in your last name:
First name = John, Last name = Smith

Detecting invalid user input with the Scanner class

Sometimes we may want to ensure that the input is valid before proceeding further. The Scanner class provides methods such as hasNext() and hasNextInt() to detect if the user has typed a valid string or integer before continuing.

For example, we can use hasNextInt() to check if the user has entered a valid number and if not, we can take suitable action such as printing an error message.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");

if (scanner.hasNextInt()) {
  int num1 = scanner.nextInt();
  System.out.println("You entered " + num1);
} else {
  System.out.println("You did not enter a number");
}

scanner.close();

If we enter an invalid number when running this program, it will print "You did not enter a number", as demonstrated below:

Enter a number:
abc
You did not enter a number

However, when we have a lot of inputs to take, we would have to add an if statement before taking each input, making our program long and complex. To avoid this scenario, the methods of the Scanner class throw a NoSuchElementException (or a subclass type such as InputMismatchException) if the entered input cannot be processed correctly.

This exception can be handled with a try/catch block, simplifying the process of error handling. We can rewrite the above program by using exception handling as shown below:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");

try {
    int num1 = scanner.nextInt();
    System.out.println("You entered " + num1);
} catch (NoSuchElementException e) {
    System.out.println("You did not enter a number");
}

scanner.close();

Commonly used Scanner class methods

The data types and the corresponding methods of the Scanner class to read a particular data type, as well as detect if an input is of the valid data type, are given below:

Data type Method to read the given data type Method to detect if the user input is valid
String (up to next whitespace character) next() hasNext()
String (entire line) nextLine() hasNextLine()
int nextInt() hasNextInt()
long nextLong() hasNextLong()
short nextShort() hasNextShort()
float nextFloat() hasNextFloat()
double nextDouble() hasNextDouble()
byte nextByte() hasNextByte()
BigDecimal nextBigDecimal() hasNextBigDecimal()
BigInteger nextBigInteger() hasNextBigInteger()

The list of all methods in the Scanner class can be found in the Java documentation.