Generate Calculator Using Switch Case in Java



In this article, we will learn how to create a simple calculator using a switch-case statement that can perform basic arithmetic operations, such as addition, subtraction, multiplication, or division. If you want to know about switch case, you can refer to this Java switch-case tutorial.

Generating a Calculator Using Switch Case

Following is the algorithm to generate a calculator using the switch case -

  • Initialize a Scanner object to take user input.

  • Take input and arithmetic operators from the user.

  • Use a switch statement to check which operator the user selected.

  • The switch statement checks the entered character, and if it matches a case, it performs the corresponding arithmetic operation.

  • After performing the operation, it prints the output to the console.

  • If the user enters a character that doesn't match any case, the default block runs, which shows an error message for invalid input.

Example

The following program accepts two integer variables, takes an operator for the operation. According to the selected operator, the program performs the respective operation and prints the result.

import java.util.Scanner;
public class ab39_CalculatorUsingSwitch {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter value of 1st number ::");
      int a = sc.nextInt();

      System.out.println("Enter value of 2nd number ::");
      int b = sc.nextInt();

      System.out.println("Select operation");
      System.out.println("Addition-a: Subtraction-s: Multiplication-m: Division-d: ");
      char ch = sc.next().charAt(0);
      switch(ch) {
         case 'a' :
         System.out.println("Sum of the given two numbers: "+(a+b));
         break;
         case 's' :
         System.out.println("Difference between the two numbers: "+(a-b));
         break;
         case 'm' :
         System.out.println("Product of the two numbers: "+(a*b));
         case 'd' :
         System.out.println("Result of the division: "+(a/b));
         break;
         default :
         System.out.println("Invalid grade");
      }
   }
}

Output

Enter value of 1st number ::
52
Enter value of 2nd number ::
85
Select operation
Addition-a: Subtraction-s: Multiplication-m: Division-d:
a
Sum of the given two numbers: 137
Manisha Chand
Manisha Chand

Words That Decode Code

Updated on: 2025-06-09T13:21:51+05:30

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started