Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 56

Calculator using switch in Java

In this lesson: Simple Java calculator with Scanner and switch — add, subtract, multiply, divide — full code with output. In Hindi & English.

What we are building

A calculator takes two numbers and an operator (+, -, *, /) and shows the result. In Java it is a great small project that brings together Scanner input, the switch statement, and simple error handling for divide by zero.

💡 A switch is ideal here — we match one value (the operator) against several exact cases.

The switch logic

double a = 10, b = 5;
char op = '+';
double result = 0;

switch (op) {
    case '+': result = a + b; break;
    case '-': result = a - b; break;
    case '*': result = a * b; break;
    case '/': result = a / b; break;
    default:  System.out.println("Invalid operator");
}
System.out.println(result);
15.0

The switch matches op to a case and runs that operation. Each case ends with break, and default catches an unknown operator.

The full program

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double a = sc.nextDouble();
        char op = sc.next().charAt(0);
        double b = sc.nextDouble();
        double result = 0;

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

We read two numbers and the operator with Scanner, choose the operation with switch, and print the result. The divide case checks for zero first.

Handling divide by zero

case '/':
    if (b == 0) {
        System.out.println("Cannot divide by zero");
    } else {
        result = a / b;
    }
    break;

Dividing by zero must be handled or the program errors. We check if (b == 0) before dividing and show a clear message. You could also catch ArithmeticException.

while (true) {
    // read a, op, b and compute with switch...
    System.out.print("Another? (y/n): ");
    if (!sc.next().equals("y")) break;
}
System.out.println("Goodbye");

A while (true) loop lets the user do many calculations. After each result, ask if they want another; anything other than "y" breaks the loop and ends.

Common mistakes

  • Forgetting break. Without it, switch falls through to the next case.
  • Not checking divide by zero. Always guard the division.
  • Reading the operator wrong. Use sc.next().charAt(0) for a single char.
  • No default case. Handle invalid operators with default.

Summary

  • A calculator picks an operation based on the operator — perfect for switch.
  • Read input with Scanner (nextDouble, next).
  • Each case does one operation and ends with break.
  • Guard the divide case against zero.
  • Add a while loop to let the user repeat.

Next, learn the switch in depth with switch-case, or read input with Scanner.

Frequently Asked Questions

How do I build a calculator in Java?
Read two numbers and an operator with Scanner, then use a switch on the operator to run the matching operation (+, -, *, /). Print the result. It combines input, switch and simple error handling.
Why use switch instead of if-else for a calculator?
A calculator compares one value (the operator) against several fixed options, which is exactly what switch is for. It is cleaner and easier to read than a long else-if chain.
How do I handle divide by zero in Java?
Check if the divisor is zero before dividing, or catch ArithmeticException. Show a message like "cannot divide by zero" instead of letting the program crash.
How do I read numbers in a Java calculator?
Use a Scanner: nextDouble() for numbers and next() for the operator character. Remember to import java.util.Scanner and create new Scanner(System.in).
How do I make the calculator repeat?
Wrap the logic in a loop, like while (true), and offer an option to quit. After each result, ask if the user wants another calculation, and break out when they choose to stop.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicJDBC MySQL Connection Your progress: 56 / 61 (92%) · Lesson 57 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free