Java Reference
In-Depth Information
A
:
Yes! Another way to convert a numeric string into its internal, binary format is to use
one of the methods defined by the
Scanner
class, packaged in
java.util
.
Scanner
reads formatted (that is, human-readable) input and converts it into its binary form.
Scanner
can be used to read input from a variety of sources, including the console
and files. Therefore, you can use
Scanner
to read a numeric string entered at the key-
board and assign its value to a variable. Although
Scanner
contains far too many
features to describe in detail, the following illustrates its basic usage.
To use
Scanner
to read from the keyboard, you must first create a
Scanner
linked to
console input. To do this, you will use the following constructor:
Scanner(InputStream
from
)
This creates a
Scanner
that uses the stream specified by
from
as a source for input. You
can use this constructor to create a
Scanner
linked to console input, as shown here:
This works because
System.in
is an object of type
InputStream
. After this line executes,
conin
can be used to read input from the keyboard.
Once you have created a
Scanner
, it is a simple matter to use it to read numeric input.
Here is the general procedure:
1.
Determine if a specific type of input is available by calling one of
Scanner
's
hasNext
X
methods, where
X
is the type of data desired.
2.
If input is available, read it by calling one of
Scanner
's
next
X
methods.
As the preceding indicates,
Scanner
defines two sets of methods that enable you to read
input. The first are the
hasNext
methods. These include methods such as
hasNextInt( )
and
hasNextDouble( )
, for example. Each of the
hasNext
methods returns
true
if the de-
sired data type is the next available item in the data stream, and
false
otherwise. For ex-
ample, calling
hasNextInt( )
returns
true
only if the next item in the stream is the human-
readable form of an integer. If the desired data is available, you can read it by calling one
of
Scanner
's
next
methods, such as
nextInt( )
or
nextDouble( )
. These methods convert
the human-readable form of the data into its internal, binary representation and return the
result. For example, to read an integer, call
nextInt( )
.
The following sequence shows how to read an integer from the keyboard.