Java Reference
In-Depth Information
the user with a subtraction question, and grading the question. Second, wrap the statements in a
loop. Third, add a loop control variable and the
loop-continuation-condition
to execute
the loop five times.
Listing 4.4 gives a program that generates five questions and, after a student answers all
five, reports the number of correct answers. The program also displays the time spent on the
test and lists all the questions.
L
ISTING
4.4
SubtractionQuizLoop.java
1
import
java.util.Scanner;
2
3
public class
SubtractionQuizLoop {
4
public static void
main(String[] args) {
5
final int
NUMBER_OF_QUESTIONS =
5
;
// Number of questions
6
int
correctCount =
0
;
// Count the number of correct answers
7
int
count =
0
;
// Count the number of questions
8
9 String output =
" "
;
// output string is initially empty
10 Scanner input =
new
Scanner(System.in);
11
12
13
long
startTime = System.currentTimeMillis();
get start time
while
(count < NUMBER_OF_QUESTIONS) {
loop
// 1. Generate two random single-digit integers
14
int
number1 = (
int
)(Math.random() *
10
);
15
int
number2 = (
int
)(Math.random() *
10
);
16
17
// 2. If number1 < number2, swap number1 with number2
18
if
(number1 < number2) {
19
int
temp = number1;
20 number1 = number2;
21 number2 = temp;
22 }
23
24
// 3. Prompt the student to answer "What is number1 - number2?"
25 System.out.print(
26
display a question
"What is "
+ number1 +
" - "
+ number2 +
"? "
);
27
int
answer = input.nextInt();
28
29
// 4. Grade the answer and display the result
30
31 System.out.println(
"You are correct!"
);
32 correctCount++;
// Increase the correct answer count
33 }
34
else
35 System.out.println(
"Your answer is wrong.\n"
+ number1
36 +
" - "
+ number2 +
" should be "
+ (number1 - number2));
37
38
// Increase the question count
39 count++;
40
41 output +=
"\n"
+ number1 +
"-"
+ number2 +
"="
+ answer +
42 ((number1 - number2 == answer) ?
" correct"
:
" wrong"
);
43
44
45
46
47
48 System.out.println(
"Correct count is "
+ correctCount +
49
if
(number1 - number2 == answer) {
grade an answer
increase correct count
increase control variable
prepare output
end loop
}
long
endTime = System.currentTimeMillis();
get end time
test time
long
testTime = endTime - startTime;
display result
"\nTest time is "
+ testTime /
1000
+
" seconds\n"
+ output);
50 }
51 }