Java Reference
In-Depth Information
means, ȒFirst call
in.next()
, then assign the result to
input
, then test whether
it equals
ÐQÑ
ȓ. This is an expression with a side effect. The primary purpose of the
expression is to serve as a test for the
while
loop, but it also does some workȌ
namely, reading the input and storing it in the variable
input
. In general, it is a
bad idea to use side effects, because they make a program hard to read and
maintain. In this case, however, that practice is somewhat seductive, because it
eliminates the control variable
done
, which also makes the code hard to read and
maintain.
The other solution is to exit the loop from the middle, either by a
return
statement or by a
break
statement (see
Advanced Topic 6.4
).
public void processInput(Scanner in)
{
while (true)
{
String input = in.next();
if (input.equalsIgnoreCase(ÐQÑ))
return;
Process data
}
}
A
DVANCED
T
OPIC
6.4: The
break
and
continue
Statements
You already encountered the
break
statement in Advanced Topic 5.2, where it
was used to exit a
switch
statement. In addition to breaking out of a
switch
statement, a
break
statement can also be used to exit a
while
,
for
, or
do
loop.
For example, the
break
statement in the following loop terminates the loop when
the end of input is reached.
while (true)
{
String input = in.next();
if (input.equalsIgnoreCase("Q"))
break;
double x = Double.parseDouble(input);
data.add(x);
}
254