Java Reference
In-Depth Information
System.out.print(", " + i);
}
System.out.println();
Sentinel Loops
Suppose you want to read a series of numbers from the user and compute their
sum. You could ask the user in advance how many numbers to read, as we did in
the last chapter, but that isn't always convenient. What if the user has a long list of
numbers to enter and hasn't counted them? One way around asking for the number
is to pick some special input value that will signal the end of input. We call this a
sentinel value.
Sentinel
A special value that signals the end of input.
For example, you could tell the user to enter the value -1 to stop entering num-
bers. But how do you structure your code to use this sentinel? In general, you'll want
to use the following approach:
sum = 0.
while (we haven't seen the sentinel) {
prompt and read.
add it to the sum.
}
This approach doesn't quite work. Suppose, for example, that the user enters the
numbers 10 , 42 , 5 , and -1 . As the pseudocode indicates, we'll prompt for and read
each of these four values and add them to our sum until we encounter the sentinel
value of -1 . We initialize the sum to 0 , so this computes (10 + 42 + 5 + -1) ,
which is 56 . But the right answer is 57 . The sentinel value of -1 isn't supposed to be
included in the sum.
This problem is a classic fencepost or “loop-and-a-half” problem: You want to
prompt for and read a series of numbers, including the sentinel, and you want to add
up most of the numbers, but you don't want to add the sentinel to the sum.
The usual fencepost solution works: We insert the first prompt-and-read instruc-
tion before the loop and reverse the order of the two steps in the body of the loop:
sum = 0.
prompt and read.
while (we haven't seen the sentinel) {
add it to the sum.
prompt and read.
}
 
Search WWH ::




Custom Search