Skip to content
Laviyx Learn

Try

Java course menu

Java while and do-while Loops: Conditions, Digits, Sentinels and Menus

Master Java while and do-while loops: loops driven by conditions, processing digits, sentinel values, menus with do-while, input validation loops with Scanner, and how to avoid infinite loops.

Beginner9 min readUpdated
On this page

A for loop is ideal for counting. A while loop is ideal when you repeat until something happens: a target is reached, a number runs out of digits, or the user types a valid answer.

while: check first#

Java
public class Main {
    public static void main(String[] args) {
        int countdown = 3;
        while (countdown > 0) {
            System.out.println(countdown + "...");
            countdown--;
        }
        System.out.println("Lift off!");
    }
}
Output
3...
2...
1...
Lift off!

Processing digits#

Peel off the last digit with % 10, remove it with / 10, and repeat until nothing is left:

Java
public class Main {
    public static void main(String[] args) {
        int n = 50721;
        int digitSum = 0;
        int reversed = 0;

        while (n > 0) {
            int digit = n % 10;
            digitSum += digit;
            reversed = reversed * 10 + digit;
            n /= 10;
        }
        System.out.println("Digit sum: " + digitSum);
        System.out.println("Reversed: " + reversed);
    }
}
Output
Digit sum: 15
Reversed: 12705

Sentinel values#

A sentinel is a special value that means "stop", such as 0 at the end of a list of prices:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double total = 0;

        System.out.println("Enter prices (0 to finish):");
        double price = in.nextDouble();
        while (price != 0) {
            total += price;
            price = in.nextDouble();
        }
        System.out.println("Total: " + total);
    }
}
Output
Enter prices (0 to finish):
120
80
45
0
Total: 245.0

Read once before the loop, then again at the end of each repetition, so the sentinel is never added.

do-while: menus#

A do ... while body runs at least once, which is exactly what a menu needs:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int choice;
        int counter = 0;

        do {
            System.out.print("1) Add one  2) Quit: ");
            choice = in.nextInt();
            if (choice == 1) {
                counter++;
                System.out.println("Counter is " + counter);
            }
        } while (choice != 2);

        System.out.println("Final value: " + counter);
    }
}
Output
1) Add one  2) Quit: 1
Counter is 1
1) Add one  2) Quit: 1
Counter is 2
1) Add one  2) Quit: 2
Final value: 2

choice is declared before the loop because the while condition is outside the loop's block.

Waiting for a condition#

while also fits simulations, where you repeat until a target is reached:

Java
public class Main {
    public static void main(String[] args) {
        double savings = 0;
        int months = 0;
        while (savings < 100_000) {
            savings += 7_500;
            savings *= 1.005;   // 0.5% monthly interest
            months++;
        }
        System.out.printf("%d months, savings %.2f%n", months, savings);
    }
}
Output
13 months, savings 100981.70

Avoiding infinite loops#

When a loop never ends, check:

  1. Is the loop variable updated inside the body?
  2. Is it updated in the right direction?
  3. Can the condition actually become false? while (x != 10) with x += 3 from 0 jumps over 10; while (x < 10) is safer.

Common mistakes#

Practice#

Practice exercise

Count the digits of int n = 9040017; with a loop that also reports 1 for n = 0.

Show solution
Java
public class Digits {
    public static void main(String[] args) {
        int n = 9040017;
        int digits = 0;
        do {
            digits++;
            n /= 10;
        } while (n != 0);
        System.out.println(digits);
    }
}
Output
7

A do-while runs at least once, so 0 correctly has one digit.

Practice exercise

Print the Collatz sequence for n = 6 (halve even numbers, replace odd n with 3n + 1, stop at 1) and the number of steps.

Show solution
Java
public class Collatz {
    public static void main(String[] args) {
        int n = 6;
        int steps = 0;
        StringBuilder sequence = new StringBuilder(String.valueOf(n));
        while (n != 1) {
            n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
            sequence.append(' ').append(n);
            steps++;
        }
        System.out.println(sequence);
        System.out.println("Steps: " + steps);
    }
}
Output
6 3 10 5 16 8 4 2 1
Steps: 8

Key takeaway#

Finished this lesson?