Java Reference
In-Depth Information
Some programmers choose numbers such as 0 or ɨ1 as sentinel values. But that is not
a good idea. These values may well be valid inputs. A better idea is to use an input
that is not a number, such as the letter Q . Here is a typical program run:
Enter value, Q to quit: 1
Enter value, Q to quit: 2
Enter value, Q to quit: 3
Enter value, Q to quit: 4
Enter value, Q to quit: Q
Average = 2.5
Maximum = 4.0
Of course, we need to read each input as a string, not a number. Once we have tested
that the input is not the letter Q , we convert the string into a number.
System.out.print(ÐEnter value, Q to quit: Ñ);
String input = in.next();
if (input.equalsIgnoreCase(ÐQÑ))
We are done
else
{
double x = Double.parseDouble(input);
. . .
}
Now we have another problem. The test for loop termination occurs in the middle of
the loop, not at the top or the bottom. You must first try to read input before you can
test whether you have reached the end of input. In Java, there isn't a readyɨmade
control structure for the pattern Ȓdo work, then test, then do more workȓ. Therefore,
we use a combination of a while loop and a boolean variable.
Sometimes, the termination condition of a loop can only be evaluated in the middle
of a loop. You can introduce a Boolean variable to control such a loop.
boolean done = false;
while (!done)
{
Print prompt
String input = read input;
if (end of input indicated)
done = true;
Search WWH ::




Custom Search