Java ProgramsControl FlowSimple ATM Menu

Simple ATM Menu in Java

intermediate·  Control Flow  ·  Switch Statement

Problem

A switch statement can dispatch to a different account operation based on a numbered menu choice, with each case handling its own logic.

Given a starting balance, a menu choice, and an amount, perform the corresponding ATM operation and report the result.

Input
balance = 1000.0, choice = 2, amount = 500.0
Output
New balance: 1500.0

Java Program

Java
public class SimpleATMMenu { public static void main(String[] args) { double balance = 1000.0; int choice = 2; double amount = 500.0; String result; switch (choice) { case 1: result = "Current balance: " + balance; break; case 2: balance += amount; result = "New balance: " + balance; break; case 3: if (amount <= balance) { // guard against withdrawing more than the balance holds balance -= amount; result = "New balance: " + balance; } else { result = "Insufficient funds"; } break; case 4: result = "Exiting"; break; default: result = "Invalid choice"; } System.out.println(result); } }

Output

New balance: 1500.0

Core Logic

Dispatching on the numbered choice routes execution straight to the matching operation, with each case doing its own balance arithmetic.

How It Works
  1. 1switch (choice) matches the numbered menu option against each case.
  2. 2Case 1 just reports the current balance, and case 2 adds amount to it for a deposit.
  3. 3Case 3 withdraws only if amount doesn't exceed the balance, guarding against an overdraft.
  4. 4Case 4 exits without changing the balance, and default reports an invalid choice.
For choice = 2 and amount = 500.0 with a starting balance of 1000.0, the deposit case adds them together, giving a new balance of 1500.0.
💡

Key Point: The withdrawal case is the only one that needs an extra guard — deposits and balance checks can never make the balance invalid, but an oversized withdrawal would.

Key Concepts

switch statementint switchconditional guard

Related Programs