Chapter Table of Contents

Ch. 8 Loops

Section Table of Contents

There is a variation of a while loop called a do-while loop. The only difference between the two is that the code inside of a do-while loop always runs at least once. This is the general format:

do { 
				// *do stuff*
} while (condition);

Notice that the condition is put at the end of the curly braces and that there is a semicolon at the end, unlike at the end of a for loop or while loop.

Here’s an example of how a do-while loop can be used:

import java.util.Scanner;

final int SECRET_NUMBER = 12;

System.out.println("Welcome to the guessing game!");
System.out.println("Guess the correct positive integer or -1 to quit.");

Scanner input = new Scanner(System.in);

int guess;
do {
     // *prompt user for their guess*
     System.out.print("Enter your guess: ");
     guess = input.nextInt();
} while (guess != SECRET_NUMBER && guess != -1);
        
if (guess == SECRET_NUMBER) { // user guessed correctly
	     System.out.println("Good job, you guessed right!");
} else { // *user quit*
      System.out.println("The secret number was " + SECRET_NUMBER);
}

Sample output 1:

Welcome to the guessing game!
Guess the correct positve integer or -1 to quit.
Enter your guess: 5
Enter your guess: 10
Enter your guess: -1
The secret number was 12

Sample output 2:

Welcome to the guessing game!
Guess the correct positve integer or -1 to quit.
Enter your guess: 34
Enter your guess: 52
Enter your guess: 12
Good job, you guessed right!

The program above is a simple guessing game. It prompts the user to enter guesses for a secret number (which is 12). It keeps asking the user to guess while their guess is incorrect and not equal to -1. (-1 is the sentinel value which the user uses to tell the program that they want to stop.)

Notice that I have to declare guess to be outside of the do-while block. If I declared it inside of the block, I would not be able to access the variable in the condition of the loop because the variable’s scope would only be within those curly braces.

💻 DoWhile.java