Write a Java Program to create a Simple Calculator using a switch case. This example allows entering two numeric values and the operator to perform calculations. Next, we used the switch case to perform computations based on the given operator.
For example, if we enter +, the switch case will perform addition. Here, we also use the default case for the wrong operator.
package SimpleNumberPrograms; import java.util.Scanner; public class Calculator { private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); double a, b, result; System.out.print("Please Enter any Two Numbers = "); a = sc.nextDouble(); b = sc.nextDouble(); System.out.print("Enter any Operator from +, - , /, *, % = "); char operator = sc.next().charAt(0); switch(operator) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': result = a / b; break; case '%': result = a % b; break; default: System.out.println("You have entered incorrect operator"); return; } System.out.printf("%.2f %c %.2f = %.2f", a, operator, b, result); } }

Let me enter the wrong symbol.
Please Enter any Two Numbers = 11 4
Enter any Operator from +, - , /, *, % = #
You have entered incorrect operator
Java Program to create a Simple Calculator using else if
In this example, we replaced the switch with else if conditions to create a simple calculator.
package SimpleNumberPrograms; import java.util.Scanner; public class Example2 { private static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); double a, b, result = 0; System.out.print("Please Enter any Two Numbers = "); a = sc.nextDouble(); b = sc.nextDouble(); System.out.print("Enter any Operator from +, - , /, *, % = "); char operator = sc.next().charAt(0); if(operator == '+') { result = a + b; } else if(operator == '-') { result = a - b; } else if(operator == '*') { result = a * b; } else if(operator == '/') { result = a / b; } else if(operator == '%') { result = a % b; } else { System.out.println("You have entered incorrect operator"); } System.out.printf("%.2f %c %.2f = %.2f", a, operator, b, result); } }
Please Enter any Two Numbers = 20 32
Enter any Operator from +, - , /, *, % = -
20.00 - 32.00 = -12.00