The program shows how to Create a Calculator using Switch Case in java. The program uses a scanner class to take the inputs from the user. The switch case is mostly used when it is necessary to give options to the users.
As we all have used a basic calculator before and we know how it works. It basically lets you input two numbers (operands) and one operator in between. The operator could be one of the following:
- + = Addition
- – = Subtraction
- * = Multiplication
- / = Division
Similarly, the program below gives you an option for the operation to perform on operands.
If you do not know about the operators in java and the switch case statements then click the link below.
Java Program to Create a Calculator using Switch Case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | //Making Calculator in java import java.util.Scanner; public class CalculatorJava { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter first numbers: "); double num1 = reader.nextDouble(); System.out.print("Enter second numbers: "); double num2 = reader.nextDouble(); System.out.print("Choose an operator (+, -, *, /): "); char operator = reader.next().charAt(0); double result; //switch case switch(operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: System.out.printf("Error! operator is not correct"); return; } //Displaying result System.out.printf("%.1f %c %.1f = %.1f", num1, operator, num2, result); } } |
Output:
Enter first numbers: 5
Enter second numbers: 3
Choose an operator (+, -, *, /): -
5.0 - 3.0 = 2.0