Beginner Logical Thinking Java

Simple Calculator Program in Java

Build a calculator in Java that reads two numbers and an operator and prints the result using a switch statement.

  • TimeO(1) per calculation
  • SpaceO(1)
  • Hints3
  • Read5 min
Quick answer

A simple calculator in Java reads two doubles with Scanner.nextDouble() and an operator with sc.next().charAt(0). A switch on the operator has a case for +, -, * and /, each ending in break. In the / case, check that the second number is not 0 before dividing. The default case handles any other operator. Since Java 14 you can also write it as a switch expression with case '+' -> a + b.

Scanner inputswitch statement with breakSwitch expressions (Java 14+)Integer and floating-point division
1

Problem statement

Write a simple calculator program in Java. Use Scanner to read two numbers and an operator (+, -, * or /), then use a switch statement to print the result.

If the operator is / and the second number is 0, print an error instead of a result. Print a message for any other operator.

Input

First number, operator, second number.

Output

"a op b = result", or an error message.

Examples

Example 1
Input12, +, 8
Output12.0 + 8.0 = 20.0

The numbers are doubles, so Java prints them with .0.

Example 2
Input9, /, 0
OutputError: cannot divide by zero

The / case checks b == 0 and stops before dividing.

Constraints

  • Numbers are read as double, so decimals are allowed
  • The operator is a single character
2

Think before you code

Reveal the questions to ask yourself first
  • Scanner has nextInt() and nextDouble(), but no nextChar(). How will you read the operator?
  • What happens in a switch if you forget break at the end of a case?
  • What does 5.0 / 0 give in Java, and why is that not a good answer for users?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Read the operator with sc.next().charAt(0).
2 Hint 2
End each case with break, or the next case also runs.
3 Hint 3
In case '/', check if (b == 0) first and return early with a message.
4

Approach

Reveal the step-by-step approach

Calculator using switch in Java

  1. Create Scanner sc = new Scanner(System.in).
  2. Read a with nextDouble(), the operator with next().charAt(0), and b with nextDouble().
  3. switch (op): one case for each operator, each ending in break.
  4. In case '/', check b == 0 first.
  5. default handles anything else.

Character cases use single quotes: case '+', not case "+". A char is compared with a char literal.

Why check for zero when doubles do not crash?

Expression Result in Java
17 / 5 (int) 3, the decimal part is dropped
(double) 17 / 5 3.4
5.0 / 0 (double) Infinity, no error
17 / 0 (int) ArithmeticException: / by zero

With doubles, dividing by zero gives Infinity instead of an error. That is not a useful answer for a calculator user, so the program checks b == 0 and prints a clear message. With ints, the same division would crash the program.

See control statements in Java for more on switch.

5

Dry run

Walk through the example step by step

Input 15, /, 4:

a = 15.0, op = '/', b = 4.0
switch (op) -> jumps straight to case '/'
    b == 0?  no
    result = 15.0 / 4.0 = 3.75
    break
print "15.0 / 4.0 = 3.75"

You do not write a separate comparison for each operator. switch goes to the matching case label, runs it, and break leaves the switch.

6

Solution

Reveal the full Java solution
Solution.java
import java.util.Scanner;

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

        System.out.print("Enter first number: ");
        double a = sc.nextDouble();
        System.out.print("Enter operator (+, -, *, /): ");
        char op = sc.next().charAt(0);
        System.out.print("Enter second number: ");
        double b = sc.nextDouble();

        double result;
        switch (op) {
            case '+':
                result = a + b;
                break;
            case '-':
                result = a - b;
                break;
            case '*':
                result = a * b;
                break;
            case '/':
                if (b == 0) {
                    System.out.println("Error: cannot divide by zero");
                    sc.close();
                    return;
                }
                result = a / b;
                break;
            default:
                System.out.println("Invalid operator: " + op);
                sc.close();
                return;
        }

        System.out.println(a + " " + op + " " + b + " = " + result);
        sc.close();
    }
}

Sample runs:

Enter first number: 12
Enter operator (+, -, *, /): +
Enter second number: 8
12.0 + 8.0 = 20.0
Enter first number: 15
Enter operator (+, -, *, /): /
Enter second number: 4
15.0 / 4.0 = 3.75
Enter first number: 9
Enter operator (+, -, *, /): /
Enter second number: 0
Error: cannot divide by zero
Enter first number: 6
Enter operator (+, -, *, /): ^
Enter second number: 2
Invalid operator: ^
  • return inside main ends the program early, so the result line is not printed after an error.
  • result is assigned in every case that reaches the final println. The return in the other paths is what lets the compiler accept that result is always set.
  • sc.close() releases the input stream when you are done.

Java calculator code with a switch expression (Java 14+)

Modern Java lets switch return a value. There is no break, and there is no fall-through.

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

    public static void main(String[] args) {
        char[] ops = {'+', '-', '*', '/', '/', '%'};
        double[][] pairs = {{20, 5}, {20, 5}, {20, 5}, {20, 8}, {20, 0}, {20, 5}};
        for (int i = 0; i < ops.length; i++) {
            try {
                double r = calculate(pairs[i][0], pairs[i][1], ops[i]);
                System.out.println(pairs[i][0] + " " + ops[i] + " " + pairs[i][1] + " = " + r);
            } catch (ArithmeticException | IllegalArgumentException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }
}
20.0 + 5.0 = 25.0
20.0 - 5.0 = 15.0
20.0 * 5.0 = 100.0
20.0 / 8.0 = 2.5
Error: cannot divide by zero
Error: invalid operator %

yield returns a value from a block inside a switch expression. The method throws an exception for bad input, and main catches it, which keeps the calculation separate from printing.

The int division trap

public class Calculator {
    public static void main(String[] args) {
        int a = 17, b = 5;
        System.out.println("int:    " + a + " / " + b + " = " + (a / b));
        System.out.println("double: " + a + " / " + b + " = " + ((double) a / b));
        System.out.println("mod:    " + a + " % " + b + " = " + (a % b));
        System.out.println("double / 0 = " + (5.0 / 0));
        try {
            System.out.println(a / 0);
        } catch (ArithmeticException e) {
            System.out.println("int / 0 -> " + e.getMessage());
        }
    }
}
int:    17 / 5 = 3
double: 17 / 5 = 3.4
mod:    17 % 5 = 2
double / 0 = Infinity
int / 0 -> / by zero

If you build the calculator with int, / drops the decimal part and division by zero throws an exception. Reading double values avoids the first problem, and the b == 0 check handles the second.

The Python version is on simple calculator program in Python. For more beginner Java practice, see array programs in Java.

TimeO(1) per calculation
SpaceO(1)
7

Review before the interview

Common mistakes

  • Forgetting break, so case '+' falls through into case '-' and the wrong result is printed.
  • Writing case "+" for a char. A char case needs single quotes: case '+'.
  • Looking for sc.nextChar(). It does not exist; use sc.next().charAt(0).
  • Using int for the numbers, so 15 / 4 prints 3 instead of 3.75.
  • Not checking b == 0, so the double version prints Infinity.

Edge cases to test

  • Division by zero: print an error message instead of Infinity or a crash.
  • Unknown operator such as ^ or %: handled by default.
  • Non-numeric input like "ten": nextDouble() throws InputMismatchException. Use hasNextDouble() to check first.
  • Negative numbers like -5: nextDouble() reads them correctly.

Interview follow-ups

  • How would you add % and a power operation using Math.pow()?
  • How would you keep the calculator running in a loop until the user types q?
  • How would you validate input with hasNextDouble() instead of letting it throw?

Keep practising

Practising for Java interviews?

CodeBegun’s Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us