Real World Example

ATM Menu Simulation

An ATM or a console banking app reads menu choices in a loop. Here the Scanner reads a fixed "session" from a String; with new Scanner(System.in) the same code would read from the keyboard.

Example

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner("1\n2 5000\n3 2000\n3 90000\n1\n4\n");
        double balance = 10000;
        boolean running = true;
        while (running && sc.hasNextInt()) {
            int choice = sc.nextInt();
            switch (choice) {
                case 1 -> System.out.println("Balance: Rs. " + balance);
                case 2 -> {
                    double amt = sc.nextDouble();
                    balance += amt;
                    System.out.println("Deposited Rs. " + amt);
                }
                case 3 -> {
                    double amt = sc.nextDouble();
                    if (amt > balance) {
                        System.out.println("Insufficient funds for Rs. " + amt);
                    } else {
                        balance -= amt;
                        System.out.println("Withdrawn Rs. " + amt);
                    }
                }
                case 4 -> {
                    System.out.println("Thank you for banking with us");
                    running = false;
                }
                default -> System.out.println("Invalid choice");
            }
        }
    }
}

Output

Balance: Rs. 10000.0
Deposited Rs. 5000.0
Withdrawn Rs. 2000.0
Insufficient funds for Rs. 90000.0
Balance: Rs. 13000.0
Thank you for banking with us