Java Reference
In-Depth Information
Recall that the following statement creates the
Scanner
object
console
and initializes it
to the standard input device:
static
Scanner console =
new
Scanner(System.in);
//Line 1
This statement is equivalent to the following statements:
static
Scanner console;
//Line 2
console =
new
Scanner(System.in);
//Line 3
The statement in Line 2 declares
console
to be the
Scanner
variable; the statement in
Line 3 initializes
console
to the standard input device. On the other hand, the statement
in Line 1 both declares and initializes the
Scanner
variable
console
.
The method
hasNext
,ofthe
class
Scanner
, returns
true
if there is an input in
the input stream, otherwise it returns
false
. In other words, the expression
console.hasNext()
evaluates to
true
if there is an input in the input stream; otherwise,
it
5
returns
false
. Therefore,
the expression
console.hasNext()
acts as
the loop
condition.
It now follows that a general form of the EOF-controlled
while
loop that uses the
Scanner
object
console
to input data is of the following form (we assume that
console
has been created and initialized using either the statement in Line 1 or the statements in
Lines 2 and 3):
while
(console.hasNext())
{
//Get the next input (token) and store it in an
//appropriate variable
//Process the data
}
In the Windows console environment, the end-of-file marker is entered using
Ctrl+z
.
(Hold the
Ctrl
key and press
z
.) In the UNIX environment, the end-of-file marker is
entered using
Ctrl+d
. (Hold the
Ctrl
key and press
d
.)
Suppose that
inFile
is a
Scanner
object initialized to the input file. In this case, the
EOF-controlled
while
loop takes the following form:
while
(inFile.hasNext())
{
//Get the next input (token) and store it in an
//appropriate variable
//Process the data
}
Search WWH ::
Custom Search