Loading

Interview Questions of do-while

Scenario 1: Validating User Input with do-while Loop

Scenario:

You are developing a console application that asks users to enter a positive number. If the user enters a negative number or zero, the program should ask again until a valid positive number is entered. The entered positive number should then be displayed.


Question:

How would you implement this input validation using a do-while loop in Java? Please write a code snippet and explain why a do-while loop is the best choice here.


Answer:

import java.util.Scanner;

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

        do {
            System.out.print("Enter a positive number: ");
            number = scanner.nextInt();
            if (number <= 0) {
                System.out.println("Invalid input. Please try again.");
            }
        } while (number <= 0);

        System.out.println("You entered: " + number);
        scanner.close();
    }
}


Explanation:

  • The do-while loop is used because we want to prompt the user at least once, regardless of their initial input.
  • The loop continues until the user enters a positive number.
  • This ensures the program always gets valid input before proceeding.


Why is do-while the best choice?

Because the user should be prompted at least once, and the condition is checked after the first input, making do-while the ideal loop for this scenario.