**Program to implement calculator in java is simple and easy calculator program in java.**

In this tutorial, we will see a simple program which is to implement **calculator program in java**.

**How to implement calculator program in java**

We know the simple mathematical operation. Using switch case we can implement calculator. Means whenever a user wants to calculate any operation its search for a case with operation and perform the mathematical operation.

We write first cases with the mathematical operation and write corresponding code in case.

Next, We take input operation from the user (addition, divide )

Search input in switch cases. The corresponding case matches then that case will get executed.

User got the result of an operation.

### Calculator program in java 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 47 48 49 50 51 52 53 54 55 56 |
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { double num1, num2; Scanner scanner = new Scanner(System.in); System.out.print("Enter first number:"); /* We are using data type double so that user * can enter integer as well as floating point * value */ num1 = scanner.nextDouble(); System.out.print("Enter second number:"); num2 = scanner.nextDouble(); System.out.print("Enter an operator (+, -, *, /): "); char operator = scanner.next().charAt(0); scanner.close(); double output; switch(operator) { case '+': output = num1 + num2; break; case '-': output = num1 - num2; break; case '*': output = num1 * num2; break; case '/': output = num1 / num2; break; /* If user enters any other operator or char apart from * +, -, * and /, then display an error message to user * */ default: System.out.printf("You have entered wrong operator"); return; } System.out.println(num1+" "+operator+" "+num2+": "+output); } } |

**Output:**

Calculator program in java

**Explanation**

**1. Program starts with initializing**

operator→ For storing the operators like +,-,/,*

num1,num2 → For storing two integers

output→ For storing the resulting value

**2. First, we take a choice of the user (+,-,/,*) then the two numbers.**

**3.Now we use switch case**

If the user enters ‘+’ as his choice then the result will be result=num1+num2

next If the user enters ‘-‘ as his choice then the result will be result=num1-num2

If the user enters ‘/’ as his choice then the result will be result=num1/num2 if num2 is not zero else flag will be zero and the output would be undefined

If the user enters ‘*’ as his choice then the result will be result=num1*num2

## Leave a Reply