Java Reference
In-Depth Information
5.2.3 Case Study: Multiple Subtraction Quiz
The Math subtraction learning tool program in ListingĀ 3.3, SubtractionQuiz.java, generates just
one question for each run. You can use a loop to generate questions repeatedly. How do you
write the code to generate five questions? Follow the loop design strategy. First identify the
statements that need to be repeated. These are the statements for obtaining two random numbers,
prompting the user with a subtraction question, and grading the question. Second, wrap the state-
ments in a loop. Third, add a loop control variable and the
loop-continuation-condition
to execute the loop five times.
ListingĀ 5.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.
VideoNote
Multiple subtraction quiz
L
ISTING
5.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
long
startTime = System.currentTimeMillis();
9 String output =
" "
;
// output string is initially empty
10 Scanner input =
new
Scanner(System.in);
11
12
get start time
while
(count < NUMBER_OF_QUESTIONS) {
loop
13
// 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
if
(number1 - number2 == answer) {
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"
);
grade an answer
increase correct count
increase control variable
prepare output
Search WWH ::
Custom Search