This is a continuation of a simple calculator program that makes use of swing. Just for recap, I covered a few topics such as how to add buttons to a panel, how to order the layout & how to add action listeners. This post will briefly explain of the logic of each action listener corresponding to each button in my calculator.
In my calculator, there're numbers 0 to 9 and other signs buttons. In this post, I will like to focus on how I develop my code regarding those arithmetic operation.
Each arithmetic operation consists of two operands, one operator and one result. Since we have only one text box, we definitely one temporary variable to store the number because the text box can hold only one number at one time. So, let's break down our process of adding numbers. It'll be like this :
1) Enter first number
2) Choose the type of operation
3) Enter second number
4) Choose = sign to get the result
As I mentioned, we need a temporary variable to store the first number, and we need to write a method to perform the arithmetic operation. So, after we enter the first number and choose an operation type, we need to clear out the first number so that when you enter a second number, the text box will start from scratch.
So, the code will look like this :
The above code is for addition. So, for other arithmetic operation, it'll be similar.
Now, what happens when you hit =. It's supposed to grab two numbers and return a result. And here's what the code looks like.
Of course, the whole project will consists of a bunch of if-else statement to capture the right button action. And note, since we're using a text box here, you can enter the numbers. However, you can't using any keys other than number keys to perform operation. Additional steps are required if we want to capture users' input from keyboards and that'll be one of my future topics.