Java Reference
In-Depth Information
This loop is infinite, because i is always 1 and i < 10 will always be true .
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 ( ) {
System.out.println( "Welcome to Java!" );
count++;
count <= 100
}
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 4.1.
L ISTING 4.1 RepeatAdditionQuiz.java
1 import java.util.Scanner;
2
3 public class RepeatAdditionQuiz {
4
public static void main(String[] args) {
5
int number1 = ( int )(Math.random() % 10 );
generate number1
generate number2
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
14
15 while ( ) {
16 System.out.print( "Wrong answer. Try again. What is "
17 + number1 + " + " + number2 + "? " );
18
19 }
20
21 System.out.println( "You got it!" );
22 }
23 }
int answer = input.nextInt();
get first answer
number1 + number2 != answer
check answer
answer = input.nextInt();
read an answer
What is 5 + 9?
Wrong answer. Try again. What is 5 + 9?
Wrong answer. Try again. What is 5 + 9?
You got it!
12
34
14
 
 
Search WWH ::




Custom Search