Java Reference
In-Depth Information
This program works as follows: The statement in Line 1 prompts the user to enter
numbers and to terminate by entering -999 . The statement in Line 2 reads the first
number and stores it in the variable number . The while statement in Line 3 checks
whether number is not equal to SENTINEL .If number is not equal to SENTINEL , the
body of the while loop executes. The statement in Line 4 updates the value of sum by
adding number to it. The statement in Line 5 increments the value of count by 1 . The
statement in Line 6 stores the next number in the variable number . The statements in
Lines 4 through 6 repeat until the program reads -999 . The statement in Line 7 outputs
the sum of the numbers, and the statements in Lines 8 through 11 output the average of
the numbers.
Notice that the statement in Line 2 initializes the LCV number . The expression number
!= SENTINEL in Line 3 checks whether the value of number is not equal to SENTINEL .
The statement in Line 6 updates the LCV number . Also, note that the program continues
to read data as long as the user has not entered -999 .
5
Next, consider another example of a sentinel-controlled while loop. In this example, the
user is prompted to enter the value to be processed. If the user wants to stop the program,
he or she can enter the value chosen for the sentinel.
EXAMPLE 5-5 TELEPHONE DIGITS
The following program reads the letter codes 'A' through 'Z' and prints the corre-
sponding telephone digit. This program uses a sentinel-controlled while loop. To stop
the program, the user is prompted for the sentinel, which is '#' . This is also an example
of a nested control structure, where if ... else , switch , and the while loop are
nested.
//********************************************************
// Program: Telephone Digits
// This is an example of a sentinel-controlled while loop.
// This program converts uppercase letters to their
// corresponding telephone digits.
//********************************************************
import javax.swing.JOptionPane;
public class TelephoneDigitProgram
{
public static void main (String[] args)
{
char letter;
//Line 1
String inputMessage;
//Line 2
String inputString;
//Line 3
String outputMessage;
//Line 4
 
Search WWH ::




Custom Search