How to Get Input with Java’s Scanner Class

By Doug Lowe

Until Java 1.5, getting text input from the user in a console-based Java program wasn’t easy. But with Java 1.5, a new class — called Scanner — was introduced to simplify the task of getting input from the user. Here, you use the Scanner class to get simple input values from the user. The techniques that I present here are used in many of the programs shown in the rest of this book.

If you’re using an older version of Java, you should still read this, because many programs use the Scanner class.

The simple program below uses the Scanner class to read an integer value from the user and then displays the value back to the console to verify that the program received the value entered by the user. Here’s a sample of the console window for this program:

Enter an integer: 5

You entered 5.

The program begins by displaying the message Enter an integer: on the first line. Then it waits for you to enter a number. When you type a number (such as 5) and press the Enter key, it displays the confirmation message (You entered 5.) on the second line.

import java.util.Scanner;@@ra1

public class ScannerApp

{

static Scanner sc = new Scanner(System.in);@@ra6

public static void main(String[] args)

{

System.out.print("Enter an integer: ");@@ra10

int x = sc.nextInt();@@ra11

System.out.println("You entered " + x + ".");@@ra12

}

}

Importing the Scanner class in Java

Before you can use the Scanner class in a program, you must import it. To do that, you code an import statement at the beginning of the program, before the class declaration:

import java.util.Scanner;

Note that java and util aren’t capitalized, but Scanner is.

If you’re using other classes in the java.util package, you can import the entire package by coding the import statement like this:

import java.util.*;

Declaring and creating a Scanner object in Java

Before you can use the Scanner class to read input from the console, you must declare a Scanner variable and create an instance of the Scanner class. You might want to create the Scanner variable as a class variable and create the Scanner object in the class variable initializer, as shown in line 6 of the program above:

static Scanner sc = new Scanner(System.in);

That way, you can use the sc variable in any method in the class.

To create a Scanner object, you use the new keyword followed by a call to the Scanner class constructor. Note that the Scanner class requires a parameter that indicates the input stream that the input comes from. You can use System.in here to specify standard keyboard console input.

Getting input

To read an input value from the user, you can use one of the methods of the Scanner class that are listed below. As you can see, the primitive data type has a separate method.

Scanner Class Methods That Get Input Values
Method Explanation
boolean nextBoolean() Reads a boolean value from the user.
byte nextByte() Reads a byte value from the user.
double nextDouble() Reads a double value from the user.
float nextFloat() Reads a float value from the user.
int nextInt() Reads an int value from the user.
String nextLine() Reads a String value from the user.
long nextLong() Reads a long value from the user.
short nextShort() Reads a short value from the user.

Notice in the first column of the table that each method listing begins with the type of the value that’s returned by the method. The nextInt method, for example, returns an int value. Also, notice that each of the methods ends with an empty set of parentheses. That means that these methods don’t require parameters. If a method does require parameters, the parameters are listed within these parentheses.

Because these methods read a value from the user and return the value, you most often use them in statements that assign the value to a variable. Line 11, for example, reads an int and assigns it to a variable named x.

When the nextInt method is executed, the program waits for the user to enter a value in the console window. To let the user know what kind of input the program expects, usually you should call the System.out.print method before you call a Scanner method to get input. Line 10 calls System.out.print to display the message Enter an integer: on the console. That way, the user knows that the program is waiting for input.

If the user enters a value that can’t be converted to the correct type, the program crashes, which means that it terminates abruptly. As the program crashes, it displays a cryptic error message that indicates what caused the failure. If you enter three instead of an actual number, for example, the console window looks something like this:

Enter an integer: three Exception in thread “main” java.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:819)

at java.util.Scanner.next(Scanner.java:1431)

at java.util.Scanner.nextInt(Scanner.java:2040)

at java.util.Scanner.nextInt(Scanner.java:2000)

at ScannerApp.main(ScannerApp.java:11)

This message indicates that an exception called InputMismatchException has occurred, which means that the program was expecting to see an integer but got something else instead. If you don’t know how to provide for exceptions like these so that the program can display a friendlier message and give the user another shot at entering a correct value, you have to put up with the fact that if the user enters incorrect data, your program crashes ungracefully.

You can prevent the nextInt and similar methods from crashing with incorrect input data by first using one of the methods listed here to test the next input to make sure it’s valid.

Scanner Class Methods That Check for Valid Input Values
Method Explanation
boolean hasNextBoolean() Returns true if the next value entered by the user is a valid boolean value.
boolean hasNextByte() Returns true if the next value entered by the user is a valid byte value.
boolean hasNextDouble() Returns true if the next value entered by the user is a valid double value.
boolean hasNextFloat() Returns true if the next value entered by the user is a valid float value.
boolean hasNextInt() Returns true if the next value entered by the user is a valid int value.
boolean hasNextLong() Returns true if the next value entered by the user is a valid long value.
boolean hasNextShort() Returns true if the next value entered by the user is a valid short value.