Calculator Program in Java
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
import java.util.*; public class BasicCalculatorExample { public static void main(String[] args) { double a; //will store the first operand double b;//will store the second operand double result;//will store the final outcome char operator;// will store the operator acting upon the above two operands Scanner rdr = new Scanner(System.in);//taking user input System.out.print("Enter two numbers: \n"); a = rdr.nextDouble(); //assigning first operand b = rdr.nextDouble(); //assigning second operand System.out.print("\n Enter one of the mentioned operators (+, -, *, /): \n"); operator = rdr.next().charAt(0);//assigning operator switch(operator) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': result = a / b; break; default: System.out.print("Please enter one of the mentioned operators."); return; } System.out.print("\nThe result is given as follows:\n"); System.out.printf(a + " " + operator + " " + b + " = " + result);//printing the result } }
Output:
Enter two numbers: 2 3 Enter one of the mentioned operators (+, -, *, /): - The result is given as follows: 2.0 - 3.0 = -1.0
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
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BasicCalculatorExample1 implements ActionListener { private static JTextField inBox;// inBox will be used to display the result BasicCalculatorExample1(){} public static void main(String[] args) { makeWindow(); } private static void makeWindow() { //Setting name of the frame JFrame fr = new JFrame("Basic Calculator"); //For closing Jframes fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(fr); fr.setSize(200, 200); //setting frame size fr.setLocationRelativeTo(null);//for centering the window fr.setVisible(true);//making the frame visible } private static void createUI(JFrame fr) { JPanel pnl = new JPanel(); //creating object of JPanel BasicCalculatorExample1 basicCalculator = new BasicCalculatorExample1(); //GridBagLayout is responsible for placing components in grid of columns and //rows GridBagLayout layout = new GridBagLayout(); //creating GridBagLayout object //Specifics constraints for components GridBagConstraints gbc = new GridBagConstraints(); //creating //GridBagConstraintsobject pnl.setLayout(layout); inBox = new JTextField(10); // Creating a text field. Also, setting default //columns to 10 inBox.setEditable(false); // The text field is not editable //Creating buttons and putting appropriate labels on it JButton btn0 = new JButton("0"); JButton btn1 = new JButton("1"); JButton btn2 = new JButton("2"); JButton btn3 = new JButton("3"); JButton btn4 = new JButton("4"); JButton btn5 = new JButton("5"); JButton btn6 = new JButton("6"); JButton btn7 = new JButton("7"); JButton btn8 = new JButton("8"); JButton btn9 = new JButton("9"); JButton btnPlus = new JButton("+"); JButton btnMinus = new JButton("-"); JButton btnDivide = new JButton("/"); JButton btnMultiply = new JButton("*"); JButton btnClear = new JButton("C"); JButton btnDot = new JButton("."); JButton btnEquals = new JButton("="); //Adding listeners to the above-created buttons btn1.addActionListener(basicCalculator); btn2.addActionListener(basicCalculator); btn3.addActionListener(basicCalculator); btn4.addActionListener(basicCalculator); btn5.addActionListener(basicCalculator); btn6.addActionListener(basicCalculator); btn7.addActionListener(basicCalculator); btn8.addActionListener(basicCalculator); btn9.addActionListener(basicCalculator); btn0.addActionListener(basicCalculator); btnPlus.addActionListener(basicCalculator); btnMinus.addActionListener(basicCalculator); btnDivide.addActionListener(basicCalculator); btnMultiply.addActionListener(basicCalculator); btnClear.addActionListener(basicCalculator); btnDot.addActionListener(basicCalculator); btnEquals.addActionListener(basicCalculator); gbc.fill = GridBagConstraints.HORIZONTAL; // Specifying constraint horizontal //Assigning the positioning of different buttons and adding them to the panel gbc.gridx = 0; gbc.gridy = 0; pnl.add(btn1, gbc); gbc.gridx = 1; gbc.gridy = 0; pnl.add(btn2, gbc); gbc.gridx = 2; gbc.gridy = 0; pnl.add(btn3, gbc); gbc.gridx = 3; gbc.gridy = 0; pnl.add(btnPlus, gbc); gbc.gridx = 0; gbc.gridy = 1; pnl.add(btn4, gbc); gbc.gridx = 1; gbc.gridy = 1; pnl.add(btn5, gbc); gbc.gridx = 2; gbc.gridy = 1; pnl.add(btn6, gbc); gbc.gridx = 3; gbc.gridy = 1; pnl.add(btnMinus, gbc); gbc.gridx = 0; gbc.gridy = 2; pnl.add(btn7, gbc); gbc.gridx = 1; gbc.gridy = 2; pnl.add(btn8, gbc); gbc.gridx = 2; gbc.gridy = 2; pnl.add(btn9, gbc); gbc.gridx = 3; gbc.gridy = 2; pnl.add(btnDivide, gbc); gbc.gridx = 0; gbc.gridy = 3; pnl.add(btnDot, gbc); gbc.gridx = 1; gbc.gridy = 3; pnl.add(btn0, gbc); gbc.gridx = 2; gbc.gridy = 3; pnl.add(btnClear, gbc); gbc.gridx = 3; gbc.gridy = 3; pnl.add(btnMultiply, gbc); gbc.gridwidth = 3; //Now, the component width will span to 3 columns gbc.gridx = 0; gbc.gridy = 4; pnl.add(inBox, gbc); //Notice the width of //text field in the output gbc.gridx = 3; gbc.gridy = 4; pnl.add(btnEquals, gbc); //Adding the panel to the frame and positioning it to center. Options like North, //West, South, East can also be tried instead of center. fr.getContentPane().add(pnl, BorderLayout.CENTER); } //This method displays text in the text field on the basis of the button pressed. //It also invokes the evaluate method. public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.charAt(0) == 'C') { inBox.setText(""); } else if (cmd.charAt(0) == '=') { inBox.setText(evaluate(inBox.getText())); } else { inBox.setText(inBox.getText() + cmd); } } //This method takes the expression in its argument and filters out the two operands and //the operator. Then, it does the calculation on the basis of the operator and returns the //result. public static String evaluate(String exp) { char[] arr = exp.toCharArray(); String a = ""; String b = ""; String op = ""; double ans = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= '0' && arr[i] <= '9' || arr[i] == '.') { if(op.isEmpty()) { a += arr[i]; } else { b += arr[i]; } } if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') { op += arr[i]; } } if (op.equals("+")) ans = (Double.parseDouble(a) + Double.parseDouble(b)); else if (op.equals("-")) ans = (Double.parseDouble(a) - Double.parseDouble(b)); else if (op.equals("/")) ans = (Double.parseDouble(a) / Double.parseDouble(b)); else ans = (Double.parseDouble(a) * Double.parseDouble(b)); return a + op + b + "=" + ans; } }
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.