Java Reference
In-Depth Information
Note
Make sure that the loop-continuation-condition eventually becomes false
so that the loop will terminate. A common programming error involves infinite loops
(i. e., the loop runs forever). If your program takes an unusually long time to run and
does not stop, it may have an infinite loop. If you are running the program from the
command window, press CTRL+C to stop it.
infinite loop
Caution
Programmers often make the mistake of executing a loop one more or less time. This
is commonly known as the off-by-one error. For example, the following loop displays
Welcome to Java 101 times rather than 100 times. The error lies in the condition,
which should be count < 100 rather than count <= 100 .
off-by-one error
int count = 0 ;
while (count <= 100 ) {
System.out.println( "Welcome to Java!" );
count++;
}
Recall that Listing 3.1, AdditionQuiz.java, gives a program that prompts the user to enter
an answer for a question on addition of two single digits. Using a loop, you can now rewrite
the program to let the user repeatedly enter a new answer until it is correct, as shown in
Listing 5.1.
L ISTING 5.1
RepeatAdditionQuiz.java
1 import java.util.Scanner;
2
3 public class RepeatAdditionQuiz {
4
public static void main(String[] args) {
generate number1
generate number2
5
int number1 = ( int )(Math.random() * 10 );
6
int number2 = ( int )(Math.random() * 10 );
7
8 // Create a Scanner
9 Scanner input = new Scanner(System.in);
10
11 System.out.print(
12
show question
"What is " + number1 + " + " + number2 + "? " );
13
int answer = input.nextInt();
get first answer
14
15 while (number1 + number2 != answer) {
16 System.out.print( "Wrong answer. Try again. What is "
17 + number1 + " + " + number2 + "? " );
18
check answer
answer = input.nextInt();
read an answer
19 }
20
21 System.out.println( "You got it!" );
22 }
23 }
What is 5 + 9? 12
Wrong answer. Try again. What is 5 + 9? 34
Wrong answer. Try again. What is 5 + 9? 14
You got it!
 
 
Search WWH ::




Custom Search