×

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:

Calculator Program in Java

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.


Related Topics

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.