Create a Calculator using Switch case

In this program, we will design a calculator using a switch case in Java. In this program, we have also use the scanner class. Scanner class is used for the user input without the scanner class we can’t take the input from the user. Scanner class is present in the util package.

Method of Scanner class

Scanner reader = new Scanner(System.in);

Java Program to create calculator using switch case

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);
    }
}

In this program first, we import the util package. After that, we use scanner class for the input and take inputs from the user and stored in the variables and variables are an integer type. After that, we use the switch case and each operation has a separate switch case. After the selection of the case the operation performed on the numbers and get the answer.



   An output of the program: Java Calculator

Enter the two Numbers: 4
6
Enter an operation(+,-,*,/): +
4+6=10

this is the output of this program I hope all of you like it. Feel free to add suggestions and any query in the below comment section.

also, learn,

Leave a Reply

Your email address will not be published. Required fields are marked *