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.

Example: Simple Calculator using switch Statement

  1. import java.util.Scanner;
  2. public class Calculator {
  3. public static void main(String[] args) {
  4. Scanner reader = new Scanner(System.in);
  5. System.out.print("Enter two numbers: ");
  6. // nextDouble() reads the next double from the keyboard
  7. double first = reader.nextDouble();
  8. double second = reader.nextDouble();
  9. System.out.print("Enter an operator (+, -, *, /): ");
  10. char operator = reader.next().charAt(0);
  11. double result;
  12. switch(operator)
  13. {
  14. case '+':
  15. result = first + second;
  16. break;
  17. case '-':
  18. result = first - second;
  19. break;
  20. case '*':
  21. result = first * second;
  22. break;
  23. case '/':
  24. result = first / second;
  25. break;
  26. // operator doesn't match any case constant (+, -, *, /)
  27. default:
  28. System.out.printf("Error! operator is not correct");
  29. return;
  30. }
  31. System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
  32. }
  33. }

When you run the program, the output will be:

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; statement ends the switch statement.

Finally, the printf statement is executed.