Java Reference
In-Depth Information
By default, a
Scanner
object reads tokens assuming they are delimited by whitespace. Whitespace corres-
ponds to any character for which the
isWhitespace()
method in the
Character
class returns
true
. Read-
ing a token therefore involves skipping over any delimiter characters until a non-delimiter character is found
and then attempting to interpret the sequence of non-delimiter characters in the way you have requested.
You can read tokens of primitive types from the scanner source using the methods found in
Table 15-9
.
TABLE 15-9
:
Calendar Field Setting Options
METHOD DESCRIPTION
nextByte()
Reads and returns the next token as type
byte
nextShort()
Reads and returns the next token as type
short
nextInt()
Reads and returns the next token as type
int
nextLong()
Reads and returns the next token as type
long
nextFloat()
Reads and returns the next token as type
float
nextDouble()
Reads and returns the next token as type
double
nextBoolean()
Reads and returns the next token as type
boolean
The first four methods each have an overloaded version that accepts an argument of type
int
specifying
the radix to be used in the interpretation of the value. All of these methods throw a
java.util.InputMismatchException
if the input does not match the regular expression for the input type
being read or a
java.util.NoSuchElementException
if the input is exhausted. Note that type
NoSuchEle-
mentException
is a superclass of type
InputMismatchException
, so you must put a
catch
clause for the
latter first if you intend to catch both types of exceptions separately. The methods can also throw an excep-
tion of type
IllegalStateException
if the scanner is closed.
If the input read does not match the token you are trying to read, the invalid input is left in the input
buffer, so you have an opportunity to try an alternative way of matching it. Of course, if it is simply erro-
neous input, you should skip over it before continuing. In this case you can call the
next()
method for the
Scanner
object, which reads the next token up to the next delimiter in the input and returns it as a
String
object.
The
Scanner
class also defines
nextBigInteger()
and
nextBigDecimal()
methods that read the next
token as a
java.math.BigInteger
object or a
java.math.BigDecimal
object, respectively. The
BigIn-
teger
class defines objects that encapsulate integers with an arbitrary number of digits and provides the
methods you need to work with such values. The
BigDecimal
class does the same thing for non-integral
values.
You have enough knowledge to try out a scanner, so let's do it.
TRY IT OUT: Using a Scanner
Here's a simple example that just reads a variety of input from the standard input stream and displays
what was read from the keyboard:
import java.util.Scanner;
import java.util.InputMismatchException;