00:00

Java Program to Make a Simple Calculator

Last updated:

This program builds a simple calculator that reads two numbers and an operator (+, -, * or /) from the user and prints the result. It is a good exercise in reading input, using a switch statement and handling errors such as an unknown operator or division by zero.

1. Simple Calculator Using a switch Statement

The operator is read as text and its first character is used in the switch. Each case does one operation, and break stops the program from running into the next case. The default branch handles any other operator.

SimpleCalculator.java
import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number: ");
        double first = scanner.nextDouble();
        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = scanner.next().charAt(0);
        System.out.print("Enter second number: ");
        double second = scanner.nextDouble();
        scanner.close();

        double result;
        switch (operator) {
            case '+':
                result = first + second;
                break;
            case '-':
                result = first - second;
                break;
            case '*':
                result = first * second;
                break;
            case '/':
                if (second == 0) {
                    System.out.println("Error: cannot divide by zero.");
                    return;
                }
                result = first / second;
                break;
            default:
                System.out.println("Error: '" + operator + "' is not a valid operator.");
                return;
        }

        System.out.println(first + " " + operator + " " + second + " = " + result);
    }
}
Output 1: addition
Enter first number: 12.5
Enter an operator (+, -, *, /): +
Enter second number: 7.5
12.5 + 7.5 = 20.0
Output 2: multiplication
Enter first number: 12.5
Enter an operator (+, -, *, /): *
Enter second number: 4
12.5 * 4.0 = 50.0
Output 3: division by zero
Enter first number: 9
Enter an operator (+, -, *, /): /
Enter second number: 0
Error: cannot divide by zero.
Output 4: invalid operator
Enter first number: 9
Enter an operator (+, -, *, /): %
Enter second number: 2
Error: '%' is not a valid operator.

2. Calculator Using a switch Expression in a Loop

Since Java 14, a switch expression with arrows (->) returns a value directly, with no break statements. This version also keeps asking for calculations until the user types q.

CalculatorLoop.java
import java.util.Scanner;

public class CalculatorLoop {

    static double calculate(double a, char op, double b) {
        return switch (op) {
            case '+' -> a + b;
            case '-' -> a - b;
            case '*' -> a * b;
            case '/' -> {
                if (b == 0) throw new ArithmeticException("division by zero");
                yield a / b;
            }
            default -> throw new IllegalArgumentException("unknown operator " + op);
        };
    }

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

        while (true) {
            System.out.print("Enter a calculation like 8 * 3 (or q to quit): ");
            String first = scanner.next();
            if (first.equalsIgnoreCase("q")) {
                break;
            }
            char op = scanner.next().charAt(0);
            double b = scanner.nextDouble();

            try {
                System.out.println("= " + calculate(Double.parseDouble(first), op, b));
            } catch (RuntimeException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
        scanner.close();
        System.out.println("Goodbye!");
    }
}
Output (with sample input)
Enter a calculation like 8 * 3 (or q to quit): 8 * 3
= 24.0
Enter a calculation like 8 * 3 (or q to quit): 100 / 8
= 12.5
Enter a calculation like 8 * 3 (or q to quit): 5 / 0
Error: division by zero
Enter a calculation like 8 * 3 (or q to quit): 7 - 10
= -3.0
Enter a calculation like 8 * 3 (or q to quit): q
Goodbye!

3. Summary

  • Read two numbers with nextDouble() and the operator with next().charAt(0).
  • A switch statement picks the operation; remember break after each case.
  • Check for division by zero and use default to reject unknown operators.
  • A switch expression with -> is shorter and returns the result directly.

Related Programs