Java Reference
In-Depth Information
How does an input method work? A token-reading method first skips any delimiters (white-
space by default), then reads a token ending at a delimiter. The token is then automatically
converted into a value of the
byte
,
short
,
int
,
long
,
float
, or
double
type for
nextByte()
,
nextShort()
,
nextInt()
,
nextLong()
,
nextFloat()
, and
nextDouble()
, respectively.
For the
next()
method, no conversion is performed. If the token does not match the expected
type, a runtime exception
java.util.InputMismatchException
will be thrown.
Both methods
next()
and
nextLine()
read a string. The
next()
method reads a string
delimited by delimiters, and
nextLine()
reads a line ending with a line separator.
InputMismatchException
next()
vs.
nextLine()
Note
The line-separator string is defined by the system. It is
\r\n
on Windows and
\n
on
UNIX. To get the line separator on a particular platform, use
line separator
String lineSeparator = System.getProperty(
"line.separator"
);
If you enter input from a keyboard, a line ends with the
Enter
key, which corresponds to
the
\n
character.
The token-reading method does not read the delimiter after the token. If the
nextLine()
method is invoked after a token-reading method, this method reads characters that start from
this delimiter and end with the line separator. The line separator is read, but it is not part of the
string returned by
nextLine()
.
Suppose a text file named
test.txt
contains a line
behavior of
nextLine()
input from file
34 567
After the following code is executed,
Scanner input =
new
Scanner(
new
File(
"test.txt"
));
int
intValue = input.nextInt();
String line = input.nextLine();
intValue
contains
34
and
line
contains the characters
' '
,
5
,
6
, and
7
.
What happens if the input is
entered from the keyboard
? Suppose you enter
34
, press the
Enter
key, then enter
567
and press the
Enter
key for the following code:
input from keyboard
Scanner input =
new
Scanner(System.in);
int
intValue = input.nextInt();
String line = input.nextLine();
You will get
34
in
intValue
and an empty string in
line
. Why? Here is the reason. The
token-reading method
nextInt()
reads in
34
and stops at the delimiter, which in this case is
a line separator (the
Enter
key). The
nextLine()
method ends after reading the line separa-
tor and returns the string read before the line separator. Since there are no characters before
the line separator,
line
is empty.
You can read data from a file or from the keyboard using the
Scanner
class. You can also
scan data from a string using the
Scanner
class. For example, the following code
scan a string
Scanner input =
new
Scanner(
"13 14"
);
int
sum = input.nextInt() + input.nextInt();
System.out.println(
"Sum is "
+ sum);
displays
The sum is 27