Java Reference
In-Depth Information
Display 2.8
Methods of the
Scanner
Class
(part 1 of 2)
The
Scanner
class can be used to obtain input from files as well as from the keyboard. However,
here we are assuming it is being used only for input from the keyboard.
To set things up for keyboard input, you need the following at the beginning of the file with the
keyboard input code:
import
java.util.Scanner;
You also need the following before the first keyboard input statement:
Scanner
Scanner_Object_Name
=
new
Scanner(System.in);
The
Scanner_Object_Name
can then be used with the following methods to read and return
various types of data typed on the keyboard.
Values to be read should be separated by whitespace characters, such as blanks and/or new lines.
When reading values, these whitespace characters are skipped. (It is possible to change the separators
from whitespace to something else, but whitespace is the default and is what we will use.)
Scanner_Object_Name
.nextInt()
Returns the next value of type
int
that is typed on the keyboard.
Scanner_Object_Name
.nextLong()
Returns the next value of type
long
that is typed on the keyboard.
Scanner_Object_Name
.nextByte()
Returns the next value of type
byte
that is typed on the keyboard.
Scanner_Object_Name
.nextShort()
Returns the next value of type
short
that is typed on the keyboard.
Scanner_Object_Name
.nextDouble()
Returns the next value of type
double
that is typed on the keyboard.
Scanner_Object_Name
.nextFloat()
Returns the next value of type
float
that is typed on the keyboard.
Scanner_Object_Name
.next()
Returns the
String
value consisting of the next keyboard characters up to, but not including, the
first delimiter character. The default delimiters are whitespace characters.
(continued)