Section 5.4 break and continue
Two additional statements may be used to modify the flow of a while-statement and other iteration statements in Java. These two statements are
break and continue.The
break statement immediately breaks out of a while-statement, regardless of the value of the conditional expression, and continues execution immediately after the while-statement block of code. The continue statement immediately stops execution of a while-statement code block, cutting it short, but rather than exit the statement, it returns to the conditional expression and evaluates it to see if another iteration should be performed.We can modify the flow of a while-statement using the strategic addition of
break and continue statements.
Subsection 5.4.1 break Statement
A
break statement is useful when you are iterating using a while-statement or other iteration statement and you determine that the entire iteration can be terminated, so flow can immediately exit the while-statement. There is no need to complete the statement code block and no need to test the condition again.
Subsection 5.4.2 continue Statement
A
continue statement also immediately stops execution of a while-statement code block, similar to break. It differs from break in that it does not cause program flow to exit the while-statement altogether. Instead, it returns immediately to the conditional expression to test if another iteration should be performed.Subsection 5.4.3 Guess a Number
Let’s write a simple game that chooses a random integer in the range [0, 9] and gives the player three chances to guess the right number. This game is implemented in Listing 5.4.1 and depends heavily on the
break and continue statements to work properly.// NumberGuess.java
import java.util.Scanner; // Import helper classes
import java.util.Random;
public class NumberGuess {
public static void main(String[] args) {
// Instantiate a Scanner to read from the terminal
Scanner scnr = new Scanner(System.in);
// Instantiate a random number generator
Random rnd = new Random();
// Pick a random number to be guessed
int answer = rnd.nextInt(10);
int count = 0; // Counter
while (true) { // Keep going
count++; // Increment count
if (count > 3) { // Max three guesses.
System.out.println("No more guesses.");
System.out.println("The correct number was " + answer);
break;
}
// Prompt user and read response.
System.out.print("Guess a number in [0, 9]: ");
int resp = scnr.nextInt();
if (resp < answer) { // Check value
System.out.println("Too low.");
continue; // Try again
} else if (resp > answer) {
System.out.println("Too high.");
continue; // Try again
} else { // Must be the right guess!
System.out.println("Correct. You win!");
break;
}
}
}
}
NumberGuess.javaThe
NumberGuess class in Listing 5.4.1 starts by importing both the Scanner and Random helper classes from java.util. The main(…) method instantiates a new Random object as well as a Scanner object that reads from System.in. It picks a random integer in [0, 9] to be guessed, initializes a counter variable and then enters a while-state with the condition true, which means that the while-statement will continue indefinitely, at least until a break statement causes the while-statement to exit. The count is incremented each time the while-statement is entered and then an if-statement tests to see of the player is out of guesses. If so, the player is informed that they are out of guesses and a break exits the loop.If the player has more guesses, the player is prompted for a new guess, which is read and compared to the answer. When the guess does not match the answer, the user is given a hint and the
continue statement immediately returns to and tests the while-statement condition, and if true, the while-statement block re-enters the code block.Here are several examples of playing the NumberGuess.java game program.
javac NumberGuess.java java NumberGuess Guess a number in [0, 9]: 5 Too high. Guess a number in [0, 9]: 4 Too high. Guess a number in [0, 9]: 2 Too high. No more chances. The correct number was 1
java NumberGuess Guess a number in [0, 9]: 5 Too high. Guess a number in [0, 9]: 3 Too high. Guess a number in [0, 9]: 2 Correct. You win!
The
break and continue statements provide an enhanced ability to customize the standard behavior of the while-statement for special-purpose computing and fine control of program flow.