Java Reference
In-Depth Information
For example, the loop for (i = 10; i <= 40; i += 5) executes (40 ɨ
10)/5 + 1 = 7 times.
A DVANCED T OPIC 6.3: The ÑLoop and a HalfÒ Problem
Reading input data sometimes requires a loop such as the following, which is
somewhat unsightly:
boolean done = false;
while (!done)
{
String input = in.next();
if (input.equalsIgnoreCase(ÐQÑ))
done = true;
else
{
Process data
}
}
The true test for loop termination is in the middle of the loop, not at the top. This is
called a Ȓloop and a halfȓ, because one must go halfway into the loop before
knowing whether one needs to terminate.
253
254
Some programmers dislike the introduction of an additional Boolean variable for
loop control. Two Java language features can be used to alleviate the Ȓloop and a
halfȓ problem. I don't think either is a superior solution, but both approaches are
fairly common, so it is worth knowing about them when reading other people's
code.
You can combine an assignment and a test in the loop condition:
while (!(input = in.next()).equalsIgnoreCase(ÐQÑ))
{
Process data
}
The expression
(input = in.next()).equalsIgnoreCase("Q")
Search WWH ::




Custom Search