Simple Calculator Program in Java

Overview

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.

Photo by Karolina Grabowska from Pexels

Program Description

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

  1. Get two numerical values from the user.
  2. Also, get the operation to be performed. (+, -, *, /, %, ^)
  3. Pass the operator value as an argument to the switch case statement.
  4. When the operator value matches any one of the case conditions, the statements under that case is executed.
  5. The result is calculated and displayed on the console.
  6. 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.
  7. 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.

Source Code

Here is the source code of a simple calculator in Java.

Output

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:

Also, download GUVI’s app to learn the latest IT skills in vernacular languages.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

L&D series: Trying out simple API tests with Postman

AbstractUser vs AbstractBaseUser In Django

Containers vs VMs

Hi and Why…your monosyllabic messages are ineffective.

Sites from where you can learn programming and many more.

Deploying Kitura Swift App to IBM Bluemix

How to deploy ReactJS and NodeJS web application in AWS EC2 with Docker and Nginx [BEGINNER GUIDE]

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Baruni Priya T S

Baruni Priya T S

More from Medium

Create a Custom Annotation In JAVA

Java Server Pages(JSP)

HashTable In Java

How to begin with JAVA