Java Program to Create a Simple Calculator

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);
	}
}
Java Program to create a Simple Calculator

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

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.