Java > Core Java > Control Flow > Do-While Loop
Do-While Loop Example: Input Validation
This example demonstrates how to use a do-while loop for input validation. The program will repeatedly prompt the user to enter a valid age until a number between 0 and 120 (inclusive) is entered.
Code Snippet
This Java code utilizes a do-while loop to validate user input for age. It prompts the user to enter their age, and the loop continues as long as the entered age is outside the valid range of 0 to 120. Inside the loop, an error message is displayed if the input is invalid. Once a valid age is entered, the loop terminates, and the program confirms the valid age.
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("Enter your age (0-120): ");
age = scanner.nextInt();
if (age < 0 || age > 120) {
System.out.println("Invalid age. Please enter a number between 0 and 120.");
}
} while (age < 0 || age > 120);
System.out.println("You entered a valid age: " + age);
scanner.close();
}
}
Concepts Behind the Snippet
The core concept here is using the do-while
loop for data validation. We want to ensure the user provides an acceptable input. The loop continues until a valid age (between 0 and 120) is entered.
Real-Life Use Case
Input validation is crucial in many applications. This technique can be applied to validate email addresses, phone numbers, passwords, and any other data where specific criteria must be met before processing.
Best Practices
Interview Tip
Be prepared to discuss different validation techniques and their trade-offs. For example, you might be asked about the advantages and disadvantages of using regular expressions vs. simple if-else statements for validation.
When to Use Them
Use a do-while loop for input validation when you want to guarantee that the user is prompted for input at least once, even if the initial input is invalid.
Alternatives
A while loop can be used for input validation as well, but it requires an initial read outside the loop. Sometimes a recursive approach might be used, but is usually less efficient and harder to read for such simple tasks.
Pros
Cons
FAQ
-
What happens if the user enters a non-integer value?
In the given code, if the user enters a non-integer value, thescanner.nextInt()
method will throw anInputMismatchException
, causing the program to crash. You should handle this exception using a try-catch block to provide a more user-friendly experience. -
How can I validate a more complex input format, like an email address?
For more complex validation scenarios, you can use regular expressions. Thejava.util.regex
package provides classes for working with regular expressions.