Java Do/While Loop

Java Do/While Loop: Ensuring Code Execution at Least Once

In Java, the do/while loop is a variation of the while loop that guarantees the code inside the loop executes at least once, regardless of the condition. This makes it ideal for scenarios where you want to perform an action at least once and then continue based on a condition. In this article, we’ll explore the syntax, use cases, and practical exercises to master the do/while loop in Java.


1. What is a Do/While Loop?

A do/while loop in Java is similar to the while loop but differs in one key aspect: the condition is checked after the loop body executes. This guarantees that the code inside the loop runs at least once, even if the condition is false from the start.

Basic Syntax of the Do/While Loop

do {
// Code to execute at least once
} while (condition);
  • do block: The code inside the do block executes first.
  • while condition: After executing the code once, the while condition is checked. If it’s true, the loop continues; if false, the loop stops.

Example:

int count = 1;

do {
System.out.println("Count is: " + count);
count++;
} while (count <= 5);

This code will print numbers from 1 to 5, just like a while loop. However, even if count were initially greater than 5, it would print once due to the do block executing first.


2. How the Do/While Loop Works

  1. Execute the Block: The code inside the do block runs first, unconditionally.
  2. Check the Condition: After executing the block once, the condition in the while statement is checked.
  3. Repeat or Exit: If the condition is true, the loop repeats; if false, the loop stops.

Example with Initial False Condition

int num = 10;

do {
System.out.println("This will print at least once, even if the condition is false.");
} while (num < 5);

In this example, even though num is not less than 5, the code in the do block executes once, printing the message.


3. When to Use a Do/While Loop

The do/while loop is especially useful when:

  • You need to ensure the code block runs at least once (e.g., asking for user input).
  • You want the loop to execute based on conditions that might change during the execution of the loop.

Examples include:

  • Input validation (prompt until valid input is provided).
  • Menus or dialogs that should display at least once.
  • Simulating repetitive actions, such as rolling a die until a certain value appears.

4. Practical Examples of the Do/While Loop

a) Input Validation

The do/while loop is commonly used to prompt for valid user input. It ensures the prompt runs at least once before checking if the input is valid.

import java.util.Scanner;

public class DoWhileInputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age;

do {
System.out.print("Please enter your age (must be positive): ");
age = scanner.nextInt();
} while (age <= 0);

System.out.println("You entered a valid age: " + age);
}
}

In this example, the loop keeps prompting the user for age until a positive value is entered.


5. Exercises

Exercise 1: Menu System

Write a program that displays a menu of options for a simple calculator. The menu should repeat until the user chooses to exit.

import java.util.Scanner;

public class MenuSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;

do {
System.out.println("\nMenu:");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.println("Addition selected.");
break;
case 2:
System.out.println("Subtraction selected.");
break;
case 3:
System.out.println("Multiplication selected.");
break;
case 4:
System.out.println("Division selected.");
break;
case 5:
System.out.println("Exiting menu.");
break;
default:
System.out.println("Invalid choice, try again.");
}
} while (choice != 5);
}
}

In this program, the menu continues to display until the user chooses option 5, which exits the program.


Exercise 2: Sum of User-Entered Numbers

Write a program that prompts the user to enter numbers and keeps a running sum. The loop should stop when the user enters 0, and then display the total sum.

import java.util.Scanner;

public class SumOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
int sum = 0;

do {
System.out.print("Enter a number (0 to stop): ");
number = scanner.nextInt();
sum += number;
} while (number != 0);

System.out.println("The total sum is: " + sum);
}
}

In this example, the loop continues to prompt the user for numbers and adds them until 0 is entered, then displays the sum.


Exercise 3: Password Checker

Create a password checker program that continues to prompt the user for a password until the correct one ("java123") is entered.

import java.util.Scanner;

public class PasswordChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String password;

do {
System.out.print("Enter the password: ");
password = scanner.nextLine();

if (!password.equals("java123")) {
System.out.println("Incorrect password. Try again.");
}
} while (!password.equals("java123"));

System.out.println("Password accepted!");
}
}

This program ensures the user is prompted at least once and will keep asking until they enter "java123".


Exercise 4: Dice Roller Game

Write a program that simulates rolling a six-sided die until a 6 is rolled. Display each roll.

public class DiceRoller {
public static void main(String[] args) {
int roll;
int count = 0;

do {
roll = (int) (Math.random() * 6) + 1;
System.out.println("Rolled: " + roll);
count++;
} while (roll != 6);

System.out.println("It took " + count + " rolls to get a 6.");
}
}

This program generates a random number between 1 and 6, simulating a die roll. It continues rolling until a 6 appears.


Summary

The do/while loop in Java is perfect for scenarios where you want to ensure that code executes at least once, even if the condition might initially be false. This makes it particularly useful for input validation, menus, and repetitive actions with changing conditions. By practicing with these exercises, you’ll gain confidence in using the do/while loop effectively in your Java programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top