Menu-Driven Calculator
This program performs arithmetic operations based on menu choice using switch.
Problem Statement
Write a Java program that performs arithmetic operations based on menu choice.
Source Code
| 1 | public class MenuCalculator { |
| 2 | public static void main(String[] args) { |
| 3 | int a = 20, b = 10; |
| 4 | int choice = 2; |
| 5 | switch(choice) { |
| 6 | case 1: System.out.println("Addition: " + (a+b) + " - Eduinq"); break; |
| 7 | case 2: System.out.println("Subtraction: " + (a-b) + " - Eduinq"); break; |
| 8 | case 3: System.out.println("Multiplication: " + (a*b) + " - Eduinq"); break; |
| 9 | case 4: System.out.println("Division: " + (a/b) + " - Eduinq"); break; |
| 10 | default: System.out.println("Invalid choice - Eduinq"); |
| 11 | } |
| 12 | } |
| 13 | } |
Program Output
Subtraction: 10 - Eduinq
Explanation
The program uses a switch statement to perform arithmetic operations based on user choice. Each case corresponds to an operation: addition, subtraction, multiplication, or division. If the choice does not match any case, the default block prints invalid choice. This demonstrates how switch can implement menu-driven systems, allowing users to select operations easily. Shows how switch can implement menu-driven calculators.