allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œThe Lord will fight for you; you need only to be still.โ€
[Exodus 14:14]



do-while


6.2.1 Basic do-while Loop

The do-while loop works like this:

  1. Run the body.

  2. Check the condition.

  3. If true, run the body again.

  4. If false, stop.

Because the check comes after the body, you guarantee at least one run โ€” no matter what.

This is perfect when you need to:

  • Prompt the user at least once,

  • Show a menu before deciding whether to repeat,

  • Run a block that generates output or setup work before validation.

Compared to while, the do-while is less common but exactly right when you must do something once before checking.

Many developers skip it and use while instead โ€” but then add extra flags or duplicate code to get the first run.
The do-while solves that cleanly.

Mini Lab

java
public class BasicDoWhile { public static void main(String[] args) { int count = 1; do { System.out.println("Count: " + count); count++; } while (count <= 5); } }

6.2.2 User Menu with do-while

A textbook do-while example is a user menu.
When you build console apps, you often show a menu, get a choice, then repeat until the user says "Exit".

You canโ€™t check the condition first โ€” you need to show the menu at least once.
The do-while is perfect for this.

It keeps your code clean: the menu display, input, and repeat check stay together in one tidy block.

This pattern appears in:

  • Admin dashboards,

  • Simple CLI tools,

  • Small games or quiz apps.

Whenever you hear โ€œshow options โžœ handle input โžœ repeat,โ€ think do-while.

Mini Lab

java
import java.util.Scanner; public class DoWhileMenu { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int choice; do { System.out.println("1. Say Hello"); System.out.println("2. Say Goodbye"); System.out.println("0. Exit"); System.out.print("Choose: "); choice = scanner.nextInt(); if (choice == 1) { System.out.println("Hello!"); } else if (choice == 2) { System.out.println("Goodbye!"); } } while (choice != 0); System.out.println("Program ended."); scanner.close(); } }

6.2.3 Input Loops with Confirmation

Another smart way to use do-while is when you want the user to confirm something.
For example, after entering data, you might ask: โ€œDo you want to enter more? Y/Nโ€

This works great because the user must always see the first prompt at least once.

This pattern avoids redundant checks and keeps the logic simple.

Mini Lab

java
import java.util.Scanner; public class DoWhileConfirm { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String again; do { System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!"); System.out.print("Do you want to enter another name? (Y/N): "); again = scanner.nextLine(); } while (again.equalsIgnoreCase("Y")); System.out.println("All done!"); scanner.close(); } }