Java Simple Calculator Program Using Switch statement – We will write a simple Java calculator program. This program will start by taking input from the user – two numbers and one operator. The operator will be from basic four operations like addition, subtraction, multiplication and division (+, – , * , / ).
Source Code Java Calculator Using switch statement
How this program will work?
Java Simple Calculator Program Using Switch
First of all, a message is shown to the user to enter two numbers. The user will enter two numbers. Another message to input an operator will cause the user to enter any one valid operator that is from +, -, * and /.
Now the program will use a switch statement to check the operator and select a suitable case to perform the required calculation.
At the end, this program displays the result on screen.
Invalid Operator Input:- If the user enters any operator other than the +, -, * or /, the program will show an error message. This message is placed in the default section of the switch statement. The statements under default section will be executed if none of the cases apply.
Sample Run of Java Calculator Program with Output
Enter two numbers: 670.90 302.20 Enter an operator (+, -, *, /): + 670.90 + 302.20 = 973.10 Enter two numbers: 44 55 Enter an operator (+, -, *, /): - 44.00 - 55.00 = -11.00 Enter two numbers: 60 10 Enter an operator (+, -, *, /): * 60.00 * 10.00 = 600.00 Enter two numbers: 30 3.5 Enter an operator (+, -, *, /): / 30.00 / 3.50 = 8.57 Enter two numbers: 10 15 Enter an operator (+, -, *, /): $ Error! operator is not correct
6,124 total views, 1 views today