Java Reference
In-Depth Information
20 System.out.println( "Your guess is too high" );
21 else
22 System.out.println( "Your guess is too low" );
23
too high?
too low?
}
// End of loop
24 }
25 }
output
line#
number
guess
6
39
11
-1
15
50
iteration 1
20
Your guess is too high
15
25
iteration 2
22
Your guess is too low
15
42
iteration 3
20
Your guess is too high
15
39
iteration 4
18
Yes, the number is 39
The program generates the magic number in line 6 and prompts the user to enter a guess con-
tinuously in a loop (lines 12-23). For each guess, the program checks whether the guess is
correct, too high, or too low (lines 17-22). When the guess is correct, the program exits the
loop (line 12). Note that guess is initialized to -1 . Initializing it to a value between 0 and 100
would be wrong, because that could be the number to be guessed.
4.2.2 Loop Design Strategies
Writing a correct loop is not an easy task for novice programmers. Consider three steps when
writing a loop.
Step 1: Identify the statements that need to be repeated.
Step 2: Wrap these statements in a loop like this:
while ( true ) {
Statements;
}
Step 3: Code the loop-continuation-condition and add appropriate statements for
controlling the loop.
while (loop-continuation-condition) {
Statements;
Additional statements for controlling the loop;
}
4.2.3 Case Study: Multiple Subtraction Quiz
The Math subtraction learning tool program in Listing 3.4, 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
VideoNote
Multiple subtraction quiz
 
 
Search WWH ::




Custom Search