Calculator Program in Java
A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case and Java swing.
Let’s start with the switch case.
Using Switch Case
Filename: BasicCalculatorExample.java
Output:
Explanation: The working of the code is quite straight-forward. We are taking input from the user to get the values of both the operands and the operator, respectively. Then, we are doing the operation, on both the operands, on the basis of the operator provided by the user. Finally, we are printing the final outcome.
Now, let’s observe the following code, which uses Java-Swing to implement a basic calculator.
Using Java Swing
Filename: BasicCalculatorExample1.java
Output:
Explanation: First, we are creating a JFrame namely Basic Calculator. Then, we are adding a panel to the frame. Alignment of the panel is center which is achieved by BorderLayout.Center. The panel contains all the buttons and the text fields. In the output, we can see the buttons are aligned horizontally. This is due to GridBagConstraints.HORIZONTAL.
GridBagConstraints also contains fields gridx and gridy which helps in the positioning of the buttons. For button 1, gridx = 0 and gridy = 0. That is why button 1 is taking the top-left position. For button =, gridx = 4 and gridy = 4. Therefore, it is taking the bottom-right position. All these buttons are filled in a grid of rows and columns. The field gridx handles the rows and gridy handles the columns. In the code, we are overriding actionPerformed() method. The method gets invoked when we press any button and also responsible for doing the calculation and rendering the output in the text field.
Designed by Elegant Themes | Powered by WordPress