×

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

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.