Java Reference
In-Depth Information
Scanning Input with the Scanner Class
Problem
You want the ease of use that the
java.util.Scanner
class brings to
simple
reading tasks.
Solution
Use
Scanner
's
next()
methods for reading.
Discussion
The
Scanner
class lets you read an input source by tokens, somewhat analogous to the
flexible in some ways (it lets you break tokens based on spaces or regular expressions) but
less in others (you need to know the kind of token you are reading). This class bears some re-
semblance to the C-language
scanf()
function, but in the
Scanner
you specify the input
token types by calling methods like
nextInt()
,
nextDouble()
, and so on. Here is a simple
example of scanning:
String sampleDate
=
"25 Dec 1988"
;
try
try
(
Scanner sDate
=
new
new
Scanner
(
sampleDate
)) {
int
int
dayOfMonth
=
sDate
.
nextInt
();
String month
=
sDate
.
next
();
int
int
year
=
sDate
.
nextInt
();
System
.
out
.
printf
(
"%d-%s-%02d%n"
,
year
,
month
,
dayOfMonth
);
}
The
Scanner
recognizes Java's eight built-in types, in addition to
BigInteger
and
BigDecimal
. It can also return input tokens as
String
s or by matching regular expressions
(see
Chapter 4
).
Table 10-3
lists the “next” methods and corresponding “has” methods; the
“has” method returns true if the corresponding “next” method would succeed. There is no
nextString()
method; just use
next()
to get the next token as a
String
.