How to Develop a Simple Calculator With Java

There are a number of ways you can go about creating a calculator program in Java. This article will provide a calculator implementation that will perform operations when provided with a string containing two operators and an operation (for example, "2 + 2"), along with a simple main method to provide a console calculator application. However, this program can be easily imported into a Swing- or AWT-based application or any other application in which an arithmetical statement needs to be interpreted from a string.

Things You'll Need

  • Java
  • Text editor or Java Integrated Development Environment (IDE)
Show More

Instructions

    • 1

      Create a new Java package called calculator. If you choose to do this with a dedicated IDE, there will probably be an option for this in the "File" menu. Otherwise, just create a folder somewhere on your hard disc called "Calculator."

    • 2

      Create the "Calculator.java" class and create a class skeleton of it. Again, if you use an IDE, there is probably an option to do this automatically, but if you elect to use a text editor, simply create an empty plain text file with ".java" for the file extension and write the following inside it:

      package calculator;
      public class Calculator {
      }

    • 3

      Declare some variables. You will want two "BigDecimals" (which must be imported from the "java.math" package) for your operands and an Integer for the operation type, as well as some constants to represent the possible operations. Edit your file so it looks like this:

      package calculator;
      import java.math.BigDecimal;

      public class Calculator {
      BigDecimal operatorOne;
      BigDecimal operatorTwo;
      Integer operationType;

      public final static Integer ADD = 0;
      public final static Integer SUB = 1;
      public final static Integer DIV = 2;
      public final static Integer MULT = 3;
      }

    • 4

      Declare methods. This class will use three methods. Though it can probably get by with only one, having many short, easy-to-understand methods is better that having fewer, more complex methods. The methods will be called "boolean parseString(String s)," "private Integer determineOperationType(String s)" and "BigDecimal performCalculation()".

      The "parseString" method will receive a string that represents an arithmetic operation -- for example "2 + 2." The "determineOperationType" method will be used by "parseString" to interpret the operation part of the statement. The method "performCalculation" does the math and returns the answer.

      Insert the following code into your class:

      boolean parseString(String s) {
      String[] operators = s.split("[ ]");
      try {
      operatorOne = new BigDecimal(operators[0]);
      operatorTwo = new BigDecimal(operators[2]);
      operationType = determineOperationType(operators[1]);
      return true;
      } catch (NumberFormatException e) {
      System.err.println("ERROR: Invalid operator.");
      return false;
      } catch (ArrayIndexOutOfBoundsException e) {
      System.err.println("ERROR: Invalid number of arguments : " + operators.length);
      return false;
      }
      }

      private Integer determineOperationType(String s) throws NumberFormatException {
      if (s.equals("+")) return ADD;
      else if (s.equals("-")) return SUB;
      else if (s.equals("/")) return DIV;
      else if (s.equals("*")) return MULT;
      else throw new NumberFormatException();
      }

      BigDecimal performCalculation() {
      try {
      if (operationType == ADD) {
      return operatorOne.add(operatorTwo);
      } else if (operationType == SUB) {
      return operatorOne.subtract(operatorTwo);
      } else if (operationType == MULT) {
      return operatorOne.multiply(operatorTwo);
      } else if (operationType == DIV) {
      return operatorOne.divide(operatorTwo);
      } else return new BigDecimal(0);
      } catch (ArithmeticException e) {
      System.err.println("Arithmetic Exception occured. Most likely this is a division by zero.");
      return new BigDecimal(0);
      }
      }

    • 5

      Write a main method. This is a simple example program to use your new "Calculator" class, though in practice you will probably want to import your class as part of another more complex program. In order for this main method to work, however, you will need to add one more import statement to the top of your class:

      import java.util.Scanner;

      "Scanner" is a convenience class designed to make it easier to read data from the console. Add the following main method to your class:

      public static void main(String[] args) {
      Calculator c = new Calculator();
      System.out.println("Enter a string to represent the calculation being performed. Place a space between each token. For example: \"2 + 2\" and not \"2+2\"");
      Scanner scan = new Scanner(System.in);
      String s = scan.nextLine();

      boolean noError = c.parseString(s);
      if (noError) {
      BigDecimal bd = c.performCalculation();
      System.out.println(bd.toPlainString());
      }
      }

Tips & Warnings

  • You may have noticed that the code above uses the "BigDecimal" class to store the operands and not the float or double primitive data types. It turns out that small inaccuracies exist in the way Java handles float and double arithmetic. Normally, these inaccuracies are small enough to not matter, however in applications where small inaccuracies are unacceptable (when dealing with currency or in a calculator, for example), the "BigDecimal" class should be used instead.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured