This project is a basic calculator application. This project serves as a beginner project to get a basic understanding of how to create a Java application that has a user interface that users can interact with.
The Java Swing library was used to create the user interface. The ActionEvent class and ActionEvent
interface were used to handle users clicking calculator buttons. The app does the basic arithmetic functions of a
calculator - namely, addition, multiplication, subtraction and division - by taking two numbers, performing the
calculation and displaying the output.
JavaJava Swing
The following are required to get started with this project:
- Create a fork of this repo.
- Clone the forked repo:
git clone https://github.com/{your_username}/BasicCalculator.git. - Launch your Java IDE.
- Use the IDE to open the project.
- Use the IDE to run the
Main.javafile located in thesrcfolder. - The calculator should be launched and ready for use.
Follow the below steps once the app is successfully launched.
Arithmetic operations require entering two numbers, specifying the operation and hitting the = sign.
- Click number buttons to enter the first number.
- Click one of the available operators:
+,-,x,÷. - Click number buttons to enter the second number.
- Click the
=button to generate a result.
The CA button is used to clear everything that is seen in the display bar.
Once this button is clicked, the app resets to its initial state.
- Click number keys, or perform an operation.
- Click the
CAbutton to remove everything from the screen.
The DEL button deletes the last (right-most) integer from the entered integers.
- Click number keys to display numbers on screen.
- Click the
DELbutton as many times as needed.
The (-) button is used to convert the entered number to it's negative form, for example, 5 to -5.
- Click number keys to display numbers on screen.
- Click the
(-)button.
In the first version of this project, the numbers inputted to the calculator were converted
from string to double. Calculations were then done with this double data type. In some cases,
the result displayed onscreen was not precise. For example, when multiplying 1.1 by 2.1 the expected result
was 2.31 but what was displayed was 2.3100000000000005.
The BigDecimal class was used to get a precise arithmetic result. Two main things were done with this class:
-
The string inputs were converted to
BigDecimalobjects. Example:BigDecimal num1 = new BigDecimal("1.1"); BigDecimal num1 = new BigDecimal("2.1"); -
Methods from the
BigDecimalclass were used for arithmetic calculations. Example:BigDecimal result = num1.multiply(num2);
While representing floating point numbers, the double data point has limited precision because of their
binary representations. BigDecimal stores numbers such that loss of precision is avoided.