In Java programming, we often need to repeatedly execute a block of code, such as printing multiple numbers or calculating a sum. In such cases, loop structures come in handy. Common loops include the while loop, do-while loop, and for loop. Today, we’ll focus on the do-while loop, which is unique because it executes the loop body first and then checks if the loop should continue. This ensures the loop body is executed at least once, avoiding issues where the loop body might not run at all.
I. Syntax Structure of the do-while Loop¶
The basic format of a do-while loop is as follows:
do {
// Loop body: Code that needs to be repeated
statement1;
statement2;
// ...
} while (conditionExpression); // Note the semicolon here
Key Points:
1. Execute the loop body first: The code inside the curly braces runs regardless of whether the condition is true or false.
2. Check the condition afterward: After executing the loop body, the condition expression following while is evaluated.
- If true, the loop body continues execution.
- If false, the loop terminates.
II. Why Use a do-while Loop?¶
The while loop executes by checking the condition first and then the loop body. If the initial condition is not met, the loop body never runs. The do-while loop, with its “execute first, check afterward” logic, ensures the loop body runs at least once. It is useful in scenarios like:
- Processing data once (e.g., reading user input, even if the input is invalid, the interaction still occurs once).
- Ensuring a task is completed at least once (e.g., checking if a file exists, even if it doesn’t, the attempt to read it is still made once).
III. Execution Flow Example¶
Let’s take a simple example to understand the execution process of do-while: Print numbers from 1 to 5.
int i = 1; // Initialize the loop variable
do {
System.out.println("Current number: " + i); // Loop body
i++; // Update the loop variable (critical: otherwise, infinite loop)
} while (i <= 5); // Check condition: Is i less than or equal to 5?
Execution Steps:
1. Execute the loop body first: Print “Current number: 1”, then i becomes 2.
2. Check the condition: i <= 5 (2 <= 5) is true, so the loop continues.
3. Execute the loop body: Print “Current number: 2”, then i becomes 3.
4. Repeat steps 2-3 until i becomes 6:
- Execute the loop body: Print “Current number: 5”, then i becomes 6.
- Check the condition: i <= 5 (6 <= 5) is false, so the loop terminates.
IV. Classic Application: User Input Interaction¶
Suppose we need to prompt the user for an integer and exit only if the input is negative. The do-while loop ensures the interaction occurs at least once, even if the user first enters a negative number.
import java.util.Scanner; // Import Scanner class to receive user input
public class DoWhileExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
do {
System.out.print("Enter an integer (negative number exits): ");
num = scanner.nextInt(); // Receive user input
if (num >= 0) {
System.out.println("You entered a positive number. Keep going!");
} else {
System.out.println("You entered a negative number. Exiting program.");
}
} while (num >= 0); // Condition: Continue looping if num >= 0
scanner.close(); // Close the Scanner
}
}
Execution Process:
- First iteration: The loop body runs regardless of whether the input is positive or negative (e.g., if the user enters 5, it prints a prompt).
- If the input is negative (e.g., -3), the condition num >= 0 becomes false, and the loop terminates.
- If the input is positive (e.g., 5), the condition is true, and the loop continues until the user enters a negative number.
V. Common Errors and Precautions¶
- Forgetting to update the loop variable: Without updating the loop variable (e.g.,
i++), the loop condition will always be true, causing an infinite loop.
// Error: Infinite loop
int i = 1;
do {
System.out.println(i);
// Missing i++, so i remains 1; condition i < 100 is always true
} while (i < 100);
-
Omitting the semicolon: The
whileclause indo-whilerequires a semicolon at the end; otherwise, a compilation error occurs. -
Avoiding always-true conditions: Ensure the loop condition will eventually become
false(e.g., the termination condition for user input must be triggerable).
VI. Summary¶
The core of the do-while loop is “execute first, then check”, guaranteeing the loop body runs at least once. It is more suitable than while in scenarios where:
- The loop body must run at least once (e.g., user input validation).
- Initial conditions are uncertain, but processing data once is necessary (e.g., reading a file, checking data validity).
Mastering do-while helps handle repetitive tasks flexibly, avoiding issues where the loop body might not execute. Remember: Updating the loop variable and ensuring the condition is correct are key to preventing infinite loops.