Introduction: Simple Java Calculator Intro
Simple Java Calculator
Intro: In this project, we will be teaching you how to create a simple calculator in Java. We will assume that you have already installed the Eclipse IDE (Integrated Development Environment). If you do not already have this software, you can download it for free at https://www.eclipse.org/downloads/. Some of the main learning objectives that you will learn while creating this application include: What a variable is and how to use it How to get input from a user and display output to the console What is method and how to write your own What an object is, and when to use them Conditional statements that will control the flow of the program How to compile and run your program in the Eclipse Environment Programming can be confusing at first. If you get lost or stuck, follow along with the included screenshots.
Note: In the code screenshots, any line that is green and preceded by two slashes (//) is a “comment”. A comment is used to annotate code and provide human-readable tips and explanations. When the program is executing, all comments are ignored and they have no effect on the program in any way. Our screenshots include comments for clarity, but they are optional and can be safely omitted.
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Step 1: Step 1: Create a New Project
Open your Eclipse Java IDE. Create a new Java Project by going to File -> New -> Java Project which can be found in the top right of the window.
Give your project a name, for our example we will name it Calculator. Once you press submit you should now see your project in the Package Explorer on the left side of the screen.
Step 2: Step 2: Create a New Class
Click File -> New -> Class to create a new class. A “class” is a way of grouping closely related code together. This breaks the program up into smaller “chunks” and makes it easier to understand. Because this is a simple program, only one class will be necessary.
Give the class a simple, logical name, such as “Calculator”. It is customary to always capitalize the first letter of a class name. Make sure that the “public static void main()” box is checked, then click “finish”.
Step 3: Step 3: Practice Creating a Variable
The first thing you will do is declare a variable. To do this simply type float a = 2; as shown below. The “float” specifies the data type, the particular one means that the variable will be a number and can include decimal values. Other variable types include int for whole numbers and String for words. The a in this code represents the variable name and the two represents the actual value assigned to the variable. “A” and “2” are both just examples, variables can have any name or value assigned as long as the name and values are both valid.
You can output information about a variable to the console by using a method called System.out.print(). The text that you want to be displayed in the console goes between the 2 parentheses. In this screenshot, we printed A and its value, which in this case is 2.
Step 4: Step 4: Executing the Program
To run this simple program, press the green arrow at the top of the screen.
If you are asked whether you want to save your work before proceeding, click OK.
After executing your code, the console should display the name and value of the variable that you specified. If you encounter any errors, make sure that your code matches the above screenshot.
Now that you have an understanding of variables and how to execute your program, we are ready to begin coding the calculator. All the prior code can be deleted for a fresh start.
Step 5: Step 5: Getting Input From the User
This calculator will add together 2 user-specified numbers. Therefore, we will start by creating 2 new float variables, “a” and “b”. These two variables cannot have the same name.
Next, create a Scanner object. This scanner, when activated, will get input from the user for later use in the program. Before using the scanner, you will need to add one line of code at the top of the class: “import.java.util.Scanner;”.
We named our scanner object keyboard because that is where the input will be coming from.
Next type out a new println to ask for the first number as shown above. This prompt will be displayed in the console.
The next line of code (a=keyboard.nextFloat();) will get the input from the user and assign that input to the variable “a”. For example, if the user enters “5”, “a” will be assigned the value 5.
Repeat this process to get the second value, and assign it to “b. Copying and pasting and changing “a” to “b” would be the quickest way.
You can print the values of A and B to the console using the same method from step 3.
Make sure to “Close” the keyboard at the end of this code, because we are done accepting input from the user at this point.
At this point it would be a good idea to compile and run this code to ensure it works as expected.
Step 6: Step 6: Ask User What Mathematical Operation to Perform
Create a third variable called “operation”. This variable’s data type will be “char” which can contain any single character. For example, a char could be ‘b’, ‘Z’ ‘+’, etc.
This char variable will hold either a plus sign, minus sign, division sign, or multiplication sign, based on what operation the user wants to perform.
Prompt the user for one of these symbols and assign the input to “operation” using the same method as above.
You can output “operation” the same as you can output “a” or “b”, as demonstrated in the above screenshot.
Step 7: Step 7: Decide What Method to Use Based on the Operator Chosen by the User
After getting the necessary user input and closing the keyboard, add in the above code. This is called a “switch” statement, and will perform a different action based on what the user put for “operation”.
For example, if the user inputted ‘+’ for operation (case ‘+’), we will Add a and b together. As shown above.
If the user chose ‘-’ for the operator, we will Subtract a from b. Create a case for each mathematical operation, and call the appropriate function for each. Shown above.
The “break” keyword appears at the end of each case, and signifies that the code for that case is completed.
Default: break; must be included at the end of the switch statement. If the users input doesn’t match any of the other cases, it will trigger the “default” case, which does nothing.
Step 8: Step 8: Writing Methods for Each Mathematical Operation
In this step we will create 4 very simple
methods, one for each mathematical operation. A “method” is a chunk of code that accomplishes one specific task. In this case, each of these methods will perform a simple mathematical calculation, and display the result to the console.
These methods must be created outside of the “Main” brackets, or the program won’t compile.
Above is a simple method to perform the addition calculation.
Follow the above screenshots to create the subtract, multiply, and divide method. They are all very similar to the add function.
Each of these methods creates a new float variable “c”, assigns the result of the math operation to c, and then displays this information to the console.
Step 9: Congratulations!
We now have a functioning calculator. When the program is executed, it should ask the user for 2 numbers and an operation, and output the result to the console, as shown below.
Note: in the interest of keeping these instructions short, this program is not perfect. For example, if the user divided by 0 it would break. Also, the program only performs one function at a time. Fixing these would require quite a bit more code and is out of the scope of this particular instructable.