Scanner

index
BASIC

A Scanner allows you to read input from the user. (You can also use it to read from other data sources, but that is not discussed here.)

Scanners are objects; there is no special syntax for them. Scanners are described here because there is no other simple way to get input from the user. For a full discussion of the Scanner class, see the Java API.

To use a Scanner, you must first import it from java.util, then construct one. Usually, you should specify System.input (the keyboard) as your data source. There is no need to construct more than one Scanner. When you are done using the Scanner, you should close it again.

import java.util.Scanner;
...
Scanner scanner = new Scanner(System.input); // use Scanner scanner.close();

You can use the Scanner to read in: an entire line as a String; the next "token" (a "word", or sequence of characters bounded by whitespace), also as a String; or any primitive type except a char. If you ask to read a primitive type, you should check first that the next input is of the correct type, or be prepared to catch an exception if it isn't.

If you want Test this Then call
An entire line scanner.hasNext() scanner.nextLine()
A token scanner.hasNext() scanner.next()
An int scanner.hasNextInt() scanner.nextInt()
A double scanner.hasNextDouble() scanner.nextDouble()
A boolean scanner.hasNextBoolean() scanner.nextBoolean()

Here are the most important exceptions to catch: