Join our newsletter for the latest updates.
Java Program to Make a Simple Calculator Using switch...case

Java Program to Make a Simple Calculator Using switch...case

In this program, you'll learn to make a simple calculator using switch..case in Java. This calculator would be able to add, subtract, multiply and divide two numbers.

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Simple Calculator using switch Statement

import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);
        System.out.print("Enter two numbers: ");

        // nextDouble() reads the next double from the keyboard
        double first = reader.nextDouble();
        double second = reader.nextDouble();

        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = reader.next().charAt(0);

        double result;

        switch(operator)
        {
            case '+':
                result = first + second;
                break;

            case '-':
                result = first - second;
                break;

            case '*':
                result = first * second;
                break;

            case '/':
                result = first / second;
                break;

            // operator doesn't match any case constant (+, -, *, /)
            default:
                System.out.printf("Error! operator is not correct");
                return;
        }

        System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
    }
}

Output

Enter two numbers: 1.5
4.5
Enter an operator (+, -, *, /): *
1.5 * 4.5 = 6.8

The * operator entered by the user is stored in the operator variable using the next() method of Scanner object.

Likewise, the two operands, 1.5 and 4.5 are stored in variables first and second respectively using the nextDouble() method of Scanner object.

Since the operator * matches the when condition '*':, the control of the program jumps to

result = first * second;

This statement calculates the product and stores in the variable result and the break; the statement ends the switch statement.

Finally, the printf statement is executed.

Note: We have used the printf() method instead of println. This is because here we are printing the formatted string. To learn more, visit the Java printf() method.