Simple Calculator Program in Java
In this blog, we will develop a simple calculator in Java programming language that can perform basic operations like addition, subtraction, multiplication, division, finding remainder and exponentiation. These operations are performed by using a switch case statement in Java.
The program should input two numerical values from the user. The program must ask the user what is the operation to be performed with the given values. According to the user’s choice, the arithmetic operation is performed and the output will be displayed on the console. Also, the user is asked whether to continue the program execution. If yes, the program execution starts again. Otherwise, the program ends.
How It Works
- Get two numerical values from the user.
- Also, get the operation to be performed. (+, -, *, /, %, ^)
- Pass the operator value as an argument to the switch case statement.
- When the operator value matches any one of the case conditions, the statements under that case is executed.
- The result is calculated and displayed on the console.
- If the operator value doesn’t match any of the case conditions, then the default block is executed which prints a message that the choice is incorrect.
- After the result is displayed, the user is asked to continue. If yes, the above statements are executed again. Else, the execution ends.
To execute the above statements repeatedly, they are put under a while loop with an initial condition of choice == ‘y’. When the user says to end the program, the choice becomes no(i.e. choice == ‘n’). Hence the program stops the execution.
Here is the source code of a simple calculator in Java.
Are you looking to master coding and crack top company interviews? Go ahead and try GUVI’s Pro Subscription to help you with everything needed to build a strong Technical Career.
Know more about GUVI:
GUVI | Learn to code in your native language
Coding Bootcamp . New Age GURUKULAM 3 months Intensive Project Based Learning program, where you will learn and gain a…
Also, download GUVI’s app to learn the latest IT skills in vernacular languages.