Java While Loops: Real-Life Examples
Applying while loops in real-world scenarios can help you understand their practical use. Below are examples demonstrating how while loops can be used in applications.
1. User Input Validation
Using a do/while
loop to repeatedly prompt the user until valid input is received.
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age;
do {
System.out.print("Enter your age (1-120): ");
age = scanner.nextInt();
} while (age < 1 || age > 120);
System.out.println("Your age is: " + age);
scanner.close();
}
}
Output:
Enter your age (1-120): 130
Enter your age (1-120): 25
Your age is: 25
Enter your age (1-120): 25
Your age is: 25
2. Menu-Driven Program
Using a while loop to display a menu and perform actions based on user choice until the user decides to exit.
import java.util.Scanner;
public class MenuProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("Menu:");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("You selected Option 1.");
break;
case 2:
System.out.println("You selected Option 2.");
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Try again.");
}
} while (choice != 3);
scanner.close();
}
}
Output:
Menu:
1. Option 1
2. Option 2
3. Exit
Enter your choice: 1
You selected Option 1.
Menu:
1. Option 1
2. Option 2
3. Exit
Enter your choice: 3
Exiting...
1. Option 1
2. Option 2
3. Exit
Enter your choice: 1
You selected Option 1.
Menu:
1. Option 1
2. Option 2
3. Exit
Enter your choice: 3
Exiting...
3. File Processing
Using a while loop to read data from a file until the end of the file is reached.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReadingExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Line 1
Line 2
Line 3
Line 2
Line 3
Key Takeaways
- While loops are versatile and can be used in various real-life applications.
- They are ideal for situations where the number of iterations depends on dynamic conditions.
- Understanding practical examples enhances your ability to implement loops effectively.