;

Java Program to Make a Simple Calculator Using switch..case Statement


Tutorialsrack 11/07/2021 Java

In this Java program, you’ll learn how to make a simple calculator using a switch..case statement. This calculator would be able to perform these operations such as add, subtract, multiply and divide two numbers. In this program, we used the following Java basics such as switch..case statement.

Here is the code of the program to make a simple calculator using a switch..case statement. 

Program - Java Program to Make a Simple Calculator Using switch..case Statement
//Java Program to Make a Simple Calculator Using switch case Statement
 
import java.util.Scanner;
 
public class JavaPrograms {
 
	public static void main(String[] args) {
 
		char operator;
		Double number1, number2, result;
 
		// create an object of Scanner class
		Scanner sc = new Scanner(System.in);
 
		// ask users to enter operator
		System.out.println("Choose an operator: +, -, *, or /");
		operator = sc.next().charAt(0);
 
		// ask users to enter numbers
		System.out.println("Enter first number");
		number1 = sc.nextDouble();
 
		System.out.println("Enter second number");
		number2 = sc.nextDouble();
 
		switch (operator) {
 
		// performs addition between numbers
		case '+':
			result = number1 + number2;
			System.out.println(number1 + " + " + number2 + " = " + result);
			break;
 
		// performs subtraction between numbers
		case '-':
			result = number1 - number2;
			System.out.println(number1 + " - " + number2 + " = " + result);
			break;
 
		// performs multiplication between numbers
		case '*':
			result = number1 * number2;
			System.out.println(number1 + " * " + number2 + " = " + result);
			break;
 
		// performs division between numbers
		case '/':
			result = number1 / number2;
			System.out.println(number1 + " / " + number2 + " = " + result);
			break;
 
		default:
			System.out.println("Invalid operator!");
			break;
		}
 
		sc.close();
	}
}
Output 1

Choose an operator: +, -, *, or /

+

Enter first number

52

Enter second number

52

52.0 + 52.0 = 104.0

Output 2

Choose an operator: +, -, *, or /

-

Enter first number

100

Enter second number

40

100.0 - 40.0 = 60.0

Output 3

Choose an operator: +, -, *, or /

/

Enter first number

100

Enter second number

5

100.0 / 5.0 = 20.0


Related Posts



Comments

Recent Posts
Tags