Menu-Driven Calculator in Java
Implement a simple calculator using switch-case based on user choice.
BeginnerModule 2: Conditional ProgramsExample 11 of 20
menu-driven-calculator.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.println("1. Addition");8 System.out.println("2. Subtraction");9 System.out.println("3. Multiplication");10 System.out.println("4. Division");11 System.out.print("Enter your choice (1-4): ");12 int choice = sc.nextInt();1314 System.out.print("Enter first number: ");15 double a = sc.nextDouble();16 System.out.print("Enter second number: ");17 double b = sc.nextDouble();1819 double result;20 switch (choice) {21 case 1:22 result = a + b;23 System.out.println("Result = " + result);24 break;25 case 2:26 result = a - b;27 System.out.println("Result = " + result);28 break;29 case 3:30 result = a * b;31 System.out.println("Result = " + result);32 break;33 case 4:34 if (b != 0) {35 result = a / b;36 System.out.println("Result = " + result);37 } else {38 System.out.println("Cannot divide by zero");39 }40 break;41 default:42 System.out.println("Invalid choice");43 }4445 sc.close();46 }47}
Output
1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice (1-4): 1 Enter first number: 5 Enter second number: 3 Result = 8.0
What's going on
We use a switch statement on the user choice to perform the selected arithmetic operation.