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.
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#
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!");
}
}3...
2...
1...
Lift off!Processing digits#
Peel off the last digit with % 10, remove it with / 10, and repeat until nothing is left:
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);
}
}Digit sum: 15
Reversed: 12705Sentinel values#
A sentinel is a special value that means "stop", such as 0 at the end of a list of prices:
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);
}
}Enter prices (0 to finish):
120
80
45
0
Total: 245.0Read 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:
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);
}
}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: 2choice 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:
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);
}
}13 months, savings 100981.70Avoiding infinite loops#
When a loop never ends, check:
- Is the loop variable updated inside the body?
- Is it updated in the right direction?
- Can the condition actually become false?
while (x != 10)withx += 3from 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
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);
}
}7A 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
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);
}
}6 3 10 5 16 8 4 2 1
Steps: 8Key takeaway#
Finished this lesson?