Do-While Loop
1. When to Use (beginner)
Do-while = "do first, ask later" — body runs at least once, condition checked after. Perfect for menus ("show menu, repeat if choice != exit").
2. Syntax + Menu Code (the classic!)
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("1.Tea 2.Coffee 0.Exit");
choice = sc.nextInt();
System.out.println("you picked " + choice);
} while (choice != 0); // semicolon MUST here!
sc.close();
}
}
// input 1,0 → prints menu twice (runs once even if choice starts 0!)
3. Do-While vs While (exam table)
| do-while | while | |
|---|---|---|
| Check | after (bottom) | before (top) |
| Min runs | 1 (always!) | 0 (may skip) |
| Semicolon | while(...); REQUIRED |
no ; after ) |
int x = 100;
do { System.out.println("runs once!"); } while (x < 0); // prints! (check after)
while (x < 0) { System.out.println("never!"); } // silent (check before)
4. Traps
- Missing
;afterwhile(...);= ERROR (only loop needing it!). - Forgetting update inside → infinite menu loop.
5. Exam Points
- Menu program + do vs while table — 5 marks, very frequent.
- Runs-once trace (condition false initially) — 3 marks, favourite.