Java ProgramsControl FlowMenu-Driven Calculator

Menu-Driven Calculator in Java

beginner·  Control Flow  ·  Switch Statement

Problem

A menu-driven program prints a fixed set of numbered choices, then switches on whichever number was picked — the switch dispatches on a menu index rather than the operator itself.

Given a menu choice from 1 to 4 and two numbers, print the operation menu and compute the result of the selected operation.

Input
choice = 3, a = 6.0, b = 7.0
Output
1. Add 2. Subtract 3. Multiply 4. Divide Result: 42.0

Java Program

Java
public class MenuDrivenCalculator { public static void main(String[] args) { double a = 6.0, b = 7.0; int choice = 3; System.out.println("1. Add"); System.out.println("2. Subtract"); System.out.println("3. Multiply"); System.out.println("4. Divide"); double result; switch (choice) { case 1: result = a + b; break; case 2: result = a - b; break; case 3: result = a * b; break; case 4: result = a / b; break; default: throw new IllegalArgumentException("Invalid choice: " + choice); // no break needed — throw exits immediately } System.out.println("Result: " + result); } }

Output

1. Add 2. Subtract 3. Multiply 4. Divide Result: 42.0

Core Logic

Printing the numbered menu first, then switching on whichever number was chosen, separates 'what the choices are' from 'what happens once one is picked'.

How It Works
  1. 1Four println calls print the menu options before any calculation happens.
  2. 2switch (choice) then matches the selected number against cases 1 through 4, each performing one arithmetic operation.
  3. 3The default case throws an exception for a choice outside the menu's range.
For choice = 3, the menu prints first, then the third case computes 6.0 * 7.0 = 42.0.
💡

Key Point: This switches on the menu position (1, 2, 3, 4), not the operator symbol itself — that's the difference from a calculator that switches directly on '+', '-', '*', '/'.

Key Concepts

switch statementmenu selectiondefault case

Related Programs