Scanner Class
Package: java.util
The Scanner
class is designed to read and parse data from an input stream. The input stream can be console input or a file stream connected to a text file.
Constructor
Constructor |
Explanation |
|
Constructs a |
|
Constructs a |
To read data from a command line console, use the constructor as follows:
static Scanner sc = new Scanner(System.in);
Methods
Method |
Explanation |
|
Returns |
|
Returns |
|
Returns |
|
Returns |
|
Returns |
|
Returns |
|
Returns |
|
Reads a |
|
Reads a |
|
Reads a |
|
Reads a |
|
Reads an |
|
Reads a |
|
Reads a |
|
Reads a |
Getting input
To read an input value from the user, you can use one of the next
methods of the Scanner
class. Each primitive data type has its own next
method. So the nextInt
method, for example, returns an int
value.
Because these methods read a value from an input source and return the value, you most often use them in statements that assign the value to a variable like this:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
In this example, the nextInt
method causes the program to wait for the user to enter a value in the console window.
To let the user know what kind of input the program expects, you should typically call the System.out.print
method before you call a Scanner
method to get input, like this:
Scanner sc = new Scanner(System.in);
System.out.println(“Please enter an integer:”);
int x = sc.nextInt();
Scanner sc = new Scanner(System.in);
System.out.println(“Please enter an integer:”);
int x;
try
{
x = sc.nextInt();
}
catch (InputMismatchException ex)
{
System.out.println(“That is not an integer!”);
}
Scanner sc = new Scanner(System.in);
System.out.println(“Please enter an integer:”);
int x;
if (sc.hasInt())
{
x = sc.nextInt();
}
else
{
x = 0;
}
Here, the variable x
is assigned the value 0
(zero) if the user does not enter a valid integer.