Java Program to Create a Simple Calculator

Write a Java Program to create a Simple Calculator using a switch case. This Java 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 +, then the switch case in this 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);
	}
}
Java Program to create a Simple Calculator 1

Let me enter 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 Java example, we replaced the switch with the 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