Java Reference
In-Depth Information
43
}
end loop
44
45
long endTime = System.currentTimeMillis();
get end time
test time
46
long testTime = endTime - startTime;
47
48 System.out.println( "Correct count is " + correctCount +
49
display result
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
50 }
51 }
What is 9 - 2? 7
You are correct!
What is 3 - 0? 3
You are correct!
What is 3 - 2? 1
You are correct!
What is 7 - 4? 4
Your answer is wrong.
7 - 4 should be 3
What is 7 - 5? 4
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
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.
5.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Ā 5.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
 
 
Search WWH ::




Custom Search