Real-Life Examples of Java Loops
Menu Systems with While Loops
While loops are useful for creating interactive menus that repeat until the user decides to exit. This pattern is common in console-based applications such as banking or ticket booking systems.
import java.util.Scanner;
public class MenuSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
boolean running = true;
while (running) {
System.out.println("\n=== BANKING MENU ===");
System.out.println("1. Check Balance");
System.out.println("2. Deposit Money");
System.out.println("3. Withdraw Money");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Your balance is $1000.00");
break;
case 2:
System.out.println("Money deposited successfully");
break;
case 3:
System.out.println("Money withdrawn successfully");
break;
case 4:
System.out.println("Thank you for banking with us!");
running = false;
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
scanner.close();
}
}
=== BANKING MENU === 1. Check Balance 2. Deposit Money 3. Withdraw Money 4. Exit Enter your choice: 1 Your balance is $1000.00 === BANKING MENU === 1. Check Balance 2. Deposit Money 3. Withdraw Money 4. Exit Enter your choice: 4 Thank you for banking with us!
Data Processing with For Loops
For loops are ideal for processing arrays or lists when the number of iterations is known. They are often used to compute statistics like totals, averages, and identifying minimum or maximum values.
public class DataProcessing {
public static void main(String[] args) {
double[] grades = {85.5, 92.0, 78.5, 88.0, 95.5, 76.0, 81.5};
double sum = 0;
double highest = grades[0];
double lowest = grades[0];
System.out.println("Processing student grades:");
for (int i = 0; i < grades.length; i++) {
System.out.println("Grade " + (i + 1) + ": " + grades[i]);
sum += grades[i];
if (grades[i] > highest) {
highest = grades[i];
}
if (grades[i] < lowest) {
lowest = grades[i];
}
}
double average = sum / grades.length;
System.out.println("\nStatistics:");
System.out.println("Average grade: " + String.format("%.2f", average));
System.out.println("Highest grade: " + highest);
System.out.println("Lowest grade: " + lowest);
System.out.println("Total students: " + grades.length);
}
}
Processing student grades: Grade 1: 85.5 Grade 2: 92.0 Grade 3: 78.5 Grade 4: 88.0 Grade 5: 95.5 Grade 6: 76.0 Grade 7: 81.5 Statistics: Average grade: 85.29 Highest grade: 95.5 Lowest grade: 76.0 Total students: 7
File Processing with Enhanced For Loops
Enhanced for loops (for-each loops) simplify iteration over collections when the index is not needed. They are useful for processing items like lines in a file or elements in a list.
import java.util.ArrayList;
import java.util.List;
public class FileProcessing {
public static void main(String[] args) {
List<String> fileLines = new ArrayList<>();
fileLines.add("2023-01-15,John Doe,150.00,Groceries");
fileLines.add("2023-01-16,Jane Smith,75.50,Restaurant");
fileLines.add("2023-01-17,Bob Johnson,45.25,Transportation");
fileLines.add("2023-01-18,Alice Brown,200.00,Shopping");
System.out.println("Expense Report:");
System.out.println("Date\t\tName\t\tAmount\tCategory");
System.out.println("============================================");
double total = 0;
int transactionCount = 0;
for (String line : fileLines) {
String[] parts = line.split(",");
String date = parts[0];
String name = parts[1];
double amount = Double.parseDouble(parts[2]);
String category = parts[3];
System.out.println(date + "\t" + name + "\t$" + amount + "\t" + category);
total += amount;
transactionCount++;
}
System.out.println("============================================");
System.out.println("Total transactions: " + transactionCount);
System.out.println("Total amount: $" + String.format("%.2f", total));
System.out.println("Average transaction: $" + String.format("%.2f", total / transactionCount));
}
}
Expense Report: Date Name Amount Category ============================================ 2023-01-15 John Doe $150.00 Groceries 2023-01-16 Jane Smith $75.50 Restaurant 2023-01-17 Bob Johnson $45.25 Transportation 2023-01-18 Alice Brown $200.00 Shopping ============================================ Total transactions: 4 Total amount: $470.75 Average transaction: $117.69
Input Validation with Do-While Loops
Do-while loops guarantee that the loop body runs at least once, making them well-suited for input validation scenarios where the program must prompt the user until valid input is provided.
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age;
String password;
boolean isValid;
do {
System.out.print("Enter your age (18-120): ");
age = scanner.nextInt();
scanner.nextLine();
if (age < 18 || age > 120) {
System.out.println("Invalid age! Please enter a value between 18 and 120.");
isValid = false;
} else {
isValid = true;
}
} while (!isValid);
do {
System.out.print("Create a password (at least 8 characters): ");
password = scanner.nextLine();
if (password.length() < 8) {
System.out.println("Password too short! Must be at least 8 characters.");
isValid = false;
} else {
isValid = true;
}
} while (!isValid);
System.out.println("\nRegistration successful!");
System.out.println("Age: " + age);
System.out.println("Password: " + "*".repeat(password.length()));
scanner.close();
}
}
Enter your age (18-120): 15 Invalid age! Please enter a value between 18 and 120. Enter your age (18-120): 25 Create a password (at least 8 characters): pass Password too short! Must be at least 8 characters. Create a password (at least 8 characters): securepassword Registration successful! Age: 25 Password: **************
Game Development with Nested Loops
Nested loops are often used in game development for tasks such as generating game boards, processing two-dimensional arrays, or simulating movements across a grid.
public class GameDevelopment {
public static void main(String[] args) {
int rows = 8;
int cols = 8;
System.out.println("Chess Board:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if ((i + j) % 2 == 0) {
System.out.print("■ ");
} else {
System.out.print("□ ");
}
}
System.out.println();
}
System.out.println("\nGame Simulation: Collecting coins in a grid");
int[][] gameGrid = {
{0, 1, 0, 1, 0},
{1, 0, 1, 0, 1},
{0, 1, 0, 1, 0},
{1, 0, 1, 0, 1}
};
int coinsCollected = 0;
for (int i = 0; i < gameGrid.length; i++) {
for (int j = 0; j < gameGrid[i].length; j++) {
if (gameGrid[i][j] == 1) {
coinsCollected++;
System.out.println("Collected coin at position (" + i + ", " + j + ")");
}
}
}
System.out.println("Total coins collected: " + coinsCollected);
}
}
Chess Board: ■ □ ■ □ ■ □ ■ □ □ ■ □ ■ □ ■ □ ■ ■ □ ■ □ ■ □ ■ □ □ ■ □ ■ □ ■ □ ■ ■ □ ■ □ ■ □ ■ □ □ ■ □ ■ □ ■ □ ■ ■ □ ■ □ ■ □ ■ □ □ ■ □ ■ □ ■ □ ■ Game Simulation: Collecting coins in a grid Collected coin at position (0, 1) Collected coin at position (0, 3) Collected coin at position (1, 0) Collected coin at position (1, 2) Collected coin at position (1, 4) Collected coin at position (2, 1) Collected coin at position (2, 3) Collected coin at position (3, 0) Collected coin at position (3, 2) Collected coin at position (3, 4) Total coins collected: 10