Simple calculator program in java using switch case – Java Program to Make a Simple Calculator using Switch Case

Simple calculator program in java using switch case: If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Java Program to Make a Simple Calculator using Switch Case

  • Write a Java program to make a simple calculator using switch case statement which perform addition, subtraction, multiplication and division or two numbers.

Given two integers and an arithmetic operator, we have to perform the specific arithmetic operation on given integer operands using a switch case statement and print the result on screen.

Java program for simple calculator using switch statement

In this java program, we first takes two integer operands and an arithmetic operator as input from user. The operator is stored in a character variable ‘op’. This calculator only support addition, subtraction, multiplication and division(+, – , * and /) operators and for any other operator it prints error message on screen saying “Unsupported Operation”. It uses switch case statement to select an arithmetic operation based on the ‘op’ variable.

Java program for simple calculator using switch statement

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to Make a Simple Calculator using Switch Statement
 */
public class Calculator {
    public static void main(String[] args) throws myException {
        int a, b;
        char op;
 
        Scanner scanner;
        scanner = new Scanner(System.in);
        // Take two numbers as input from user
        System.out.println("Enter Two Integers");
        a = scanner.nextInt();
        b = scanner.nextInt();
 
        // Taking operator as input from user
        System.out.println("Enter an Operator");
        op = scanner.next().charAt(0);
 
        switch (op) {
        case '+':
            System.out.format("%d + %d = %d\n", a, b, a + b);
            break;
        case '-':
            System.out.format("%d - %d = %d\n", a, b, a - b);
            break;
        case '*':
            System.out.format("%d * %d = %d\n", a, b, a * b);
            break;
        case '/':
            System.out.format("%d / %d = %d\n", a, b, a / b);
            break;
        default:
            System.out.println("ERROR: Unsupported Operation");
        }
    }
}

Output

Enter Two Integers
10 4
Enter an Operator
+
10 + 4 = 14
Enter Two Integers
4 7
Enter an Operator
*
4 * 7 = 28
Enter Two Integers
2 3
Enter an Operator
^
ERROR: Unsupported Operation