Curriculum
In Java, the do while
loop is a control flow statement that allows you to execute a block of code at least once and repeatedly as long as a certain condition is true. The syntax of a do while
loop is as follows:
do { // code to be executed at least once and repeatedly while condition is true } while (condition);
The do
statement executes the code in the loop at least once, and then the while
statement tests the condition. If the condition is true, the loop will execute again, and it will continue to do so until the condition becomes false.
Here’s an example of a simple do while
loop:
int i = 0; do { System.out.println(i); i++; } while (i < 5);
In this example, the loop will always execute at least once, regardless of the value of i
. During each iteration, the value of i
is printed to the console, and then i
is incremented by 1. The loop will continue to execute until i
is equal to 5.
Another use of a do while
loop is to read input from the user until a specific condition is met. Here’s an example:
import java.util.Scanner; Scanner scanner = new Scanner(System.in); String input; do { System.out.print("Enter a command (or 'quit' to exit): "); input = scanner.nextLine(); // process the command here } while (!input.equals("quit")); scanner.close();
In this example, the loop will always execute at least once, prompting the user to enter a command. The loop will continue to execute until the user enters the word “quit”. The loop will then terminate, and the program will continue executing.
It’s important to make sure that the condition used in a do while
loop eventually becomes false, or the loop will continue to execute indefinitely, leading to an infinite loop. Infinite loops can cause your program to crash or become unresponsive, so it’s important to use conditions that will eventually become false.