Java Reference
In-Depth Information
What is 9 - 2?
You are correct!
What is 3 - 0?
You are correct!
What is 3 - 2?
You are correct!
What is 7 - 4?
Your answer is wrong.
7 - 4 should be 3
What is 7 - 5?
Your answer is wrong.
7 - 5 should be 2
Correct count is 3
Test time is 1021 seconds
9-2=7 correct
3-0=3 correct
3-2=1 correct
7-4=4 wrong
7-5=4 wrong
7
3
1
4
4
The program uses the control variable count to control the execution of the loop. count
is initially 0 (line 7) and is increased by 1 in each iteration (line 39). A subtraction question is
displayed and processed in each iteration. The program obtains the time before the test starts
in line 8 and the time after the test ends in line 45, and computes the test time in line 46. The
test time is in milliseconds and is converted to seconds in line 49.
4.2.4 Controlling a Loop with a Sentinel Value
Another common technique for controlling a loop is to designate a special value when read-
ing and processing a set of values. This special input value, known as a sentinel value , signi-
fies the end of the input. A loop that uses a sentinel value to control its execution is called a
sentinel-controlled loop.
Listing 4.5 writes a program that reads and calculates the sum of an unspecified number of
integers. The input 0 signifies the end of the input. Do you need to declare a new variable for
each input value? No. Just use one variable named data (line 12) to store the input value and
use a variable named sum (line 15) to store the total. Whenever a value is read, assign it to
data and, if it is not zero, add it to sum (line 17).
sentinel value
sentinel-controlled loop
L ISTING 4.5 SentinelValue.java
1 import java.util.Scanner;
2
3 public class SentinelValue {
4 /** Main method */
5 public static void main(String[] args) {
6 // Create a Scanner
7 Scanner input = new Scanner(System.in);
8
9 // Read an initial data
10 System.out.print(
11
"Enter an integer (the input ends if it is 0): " );
12
int data = input.nextInt();
input
 
 
Search WWH ::




Custom Search