The do-while Loop

Run first, check later

A do-while loop runs its body first, then checks the condition. So it always runs at least once:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int guess;
        do {
            System.out.println("Guess the number (1-10):");
            guess = sc.nextInt();
        } while (guess != 7);
        System.out.println("Correct!");
    }
}

Input (what the user types)

3
9
7

Output

Guess the number (1-10):
Guess the number (1-10):
Guess the number (1-10):
Correct!

We need to ask at least once before we can check the guess, so do-while fits perfectly.

Common mistake: Notice the semicolon after while (guess != 7); – a do-while needs it.

HOME LABS COMMUNITY DASHBOARD