Menu-Driven Calculator

Implement a simple calculator using switch-case based on user choice.

BeginnerTopic: Module 2: Conditional Programs
Back

Java Menu-Driven Calculator Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("1. Addition");
        System.out.println("2. Subtraction");
        System.out.println("3. Multiplication");
        System.out.println("4. Division");
        System.out.print("Enter your choice (1-4): ");
        int choice = sc.nextInt();

        System.out.print("Enter first number: ");
        double a = sc.nextDouble();
        System.out.print("Enter second number: ");
        double b = sc.nextDouble();

        double result;
        switch (choice) {
            case 1:
                result = a + b;
                System.out.println("Result = " + result);
                break;
            case 2:
                result = a - b;
                System.out.println("Result = " + result);
                break;
            case 3:
                result = a * b;
                System.out.println("Result = " + result);
                break;
            case 4:
                if (b != 0) {
                    result = a / b;
                    System.out.println("Result = " + result);
                } else {
                    System.out.println("Cannot divide by zero");
                }
                break;
            default:
                System.out.println("Invalid choice");
        }

        sc.close();
    }
}
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

Understanding Menu-Driven Calculator

We use a switch statement on the user choice to perform the selected arithmetic operation.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents