Calculator which follows BODMAS rules in Java

Today we’ll implement a calculator that follows the BODMAS rule using Java.

BODMAS expands to – Bracket Of Division Multiplication Addition Subtraction. It is a global norm for performing arithmetic calculations.  Following this order, we achieve correct arithmetic results.

The example expressions undergoing BODMAS evaluation are in the code itself. The resultant output has the solved answers for these expressions.

Implementation of BODMAS in Java

First, we have to import java.util.Stack; package  to run the below code

  • We will push our elements into the stack.
  • Parse the expression to identify the tokens.
  • The token can be Operand or Operator.
  • If brackets come, the highest priority is given to its enclosing expression.
  • The rest of the stack contains the remaining tokens.
  • Evaluation of remaining tokens takes place.
  • We will repeat this procedure until the result reaches the top of the stack.

The below code is the updated version of the previous code: (Updated code submitted by Saima Shamim)

import java.util.Stack;

public class BODMAS {
    public static void main(String args[]) 
    {
        System.out.println("**Outputs**");
        System.out.println(solveExp("50 + 3 * (80/40)")); 
        System.out.println(solveExp("60 + 7 * 100/25")); 
        System.out.println(solveExp("100 - 8 * 20")); 
        System.out.println(solveExp("90 * (91 - 60)"));
        try {
            System.out.println(solveExp("1000 / 0"));
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }

    public static int solveExp(String expression) {
        char[] arr_token = expression.toCharArray();
        Stack<Integer> int_value = new Stack<>();
        Stack<Character> opertor_value = new Stack<>();
        for(int i=0; i < arr_token.length; i++) {
            if(arr_token[i] == ' ')
                continue;
            if (Character.isDigit(arr_token[i])) { 
                StringBuilder str = new StringBuilder();
                while (i < arr_token.length && Character.isDigit(arr_token[i])) {
                    str.append(arr_token[i]);
                    i++; // increment the index
                }
                i--; // decrement the index to ensure the correct character is processed
                int_value.push(Integer.parseInt(str.toString())); 
            } else if (arr_token[i] == '(') {
                opertor_value.push(arr_token[i]);
            } else if (arr_token[i] == ')') { 
                while (opertor_value.peek() != '(') {
                    int_value.push(applyOperation(opertor_value.pop(), int_value.pop(), int_value.pop())); 
                }
                opertor_value.pop();
            } else if (arr_token[i] == '+' || arr_token[i] == '-' || arr_token[i] == '*' || arr_token[i] == '/') {
                while (!opertor_value.empty() && hasPrecedence(arr_token[i], opertor_value.peek())) {
                    int_value.push(applyOperation(opertor_value.pop(), int_value.pop(), int_value.pop()));
                }
                opertor_value.push(arr_token[i]);    
            }
        }
        while (!opertor_value.empty()) {
            int_value.push(applyOperation(opertor_value.pop(), int_value.pop(), int_value.pop())); 
        }
        return int_value.pop();
    } 

    public static boolean hasPrecedence(char oper1, char oper2) { 
        if (oper2 == '(' || oper2 == ')') 
            return false; 
        if ((oper1 == '/' || oper1 == '*') && (oper2 == '+' || oper2 == '-')) 
            return false; 
        return true;
    }
    
    public static int applyOperation(char oper, int var2, int var1) { 
        switch (oper) { 
            case '+': 
                return var1 + var2; 
            case '-': 
                return var1 - var2; 
            case '*': 
                return var1 * var2; 
            case '/': 
                if (var2 == 0) 
                    throw new ArithmeticException("Division by zero not possible!"); 
                return var1 / var2; 
        } 
        return 0;
    }
}

Explanation

In the above code, BODMAS is the main class. It contains the following methods :

  • void main(String args[])
  • int solveExp(String expression)
  • boolean hasPrecedence(char oper1, char oper2)
  • int applyOperation(char oper, int var2, int var1)

The void main() section comprises of the expressions yet to undergo evaluation.

The int solveExp() basically brings everything to a character array, to parse the expression. Here, char[] arr_token is the character array storing the parse tokens. For pushing numbers onto stack, we have ‘int_value’ and for pushing operators onto stack, we have ‘operator_value’. After the declaration of variables, we move to the parsing expression. Parsing the expression requires StringBuilder class, with its instance ‘str’.

Moreover, to check the precedence of operators, boolean hasPrecedence() is given. Since it is a boolean, returning true or false indicates the priority. Moving on to applyOperation().

int applyOperation() is the actual calculator. In a switch case, the operator determines the performing arithmetic operation. Special vigilance is by the exception block for division by zero, as in the code.

Output :

**Outputs**
56
88
-60
2790
Division by zero not possible!

Thus, the following code produces the following output. Prior knowledge of Java syntax, concepts, and methods would come in handy.

To learn more about stack operations, refer the following links :

How Java objects are stored in memory

2 responses to “Calculator which follows BODMAS rules in Java”

  1. Lalit kumar singh says:

    this program use one bracket is actual answer but more then one brackets use than the answer is not correct

    please check this program

    import java.util.*;

    public class Bodmass {

    public static int solved(String equation){
    char[] arr_val = equation.toCharArray();
    String sg = “”;
    Stack values = new Stack();
    Stack sym_obj = new Stack();
    for (int i = 0; i = ‘0’ && arr_val[i] <= '9'){
    sg += arr_val[i];
    values.push(Integer.parseInt(sg.toString()));
    sg = "";
    }
    else if (arr_val[i] == '(')
    sym_obj.push(arr_val[i]);
    else if (arr_val[i] == ')') {
    while (sym_obj.peek() != '(')
    values.push(operat(sym_obj.pop(), values.pop(), values.pop()));
    sym_obj.pop();
    }
    else if (arr_val[i] == '+' || arr_val[i] == '-' ||
    arr_val[i] == '*' || arr_val[i] == '/')
    {
    while (!sym_obj.empty() && Precedence(arr_val[i], sym_obj.peek()))
    values.push(operat(sym_obj.pop(), values.pop(), values.pop()));
    sym_obj.push(arr_val[i]);
    }
    }
    while (!sym_obj.empty())
    values.push(operat(sym_obj.pop(), values.pop(), values.pop()));

    return values.pop();
    }

    public static boolean Precedence(char oper_1, char oper_2){
    if (oper_2 == '(' || oper_2 == ')')
    return false;
    if ((oper_1 == '*' || oper_1 == '/') && (oper_2 == '+' || oper_2 == '-'))
    return false;
    else
    return true;
    }

    public static int operat(char oper, int var2, int var1)
    {
    switch (oper){
    case '+':
    return var1 + var2;
    case '-':
    return var1 – var2;
    case '*':
    return var1 * var2;
    case '/':
    if (var2 == 0)
    throw new
    ArithmeticException("division by zero.. impossible!");
    return var1 / var2;
    }
    return 0;
    }

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter the equation: ");
    String str = input.nextLine();
    System.out.println(Bodmass.solved(str));
    }
    }

    • Sivarajavel says:

      class BODMAS
      {
      public static String getString()throws java.io.IOException
      {
      return ((new java.io.BufferedReader(new java.io.InputStreamReader(System.in))).readLine());
      }
      public static java.util.ArrayList split(String expression)
      {
      String s=new String();
      java.util.ArrayList al=new java.util.ArrayList();
      for(int i=0;i=48&&expression.charAt(i)<=57)
      s+=expression.charAt(i);
      else
      {
      al.add(s);
      s="";
      s+=expression.charAt(i);
      al.add(s);
      s="";
      }
      if(i==(expression.length()-1))
      al.add(s);
      }
      return al;
      }
      public static int sum(int n1,int n2,char c)
      {
      return (c=='%'?n1%n2:(c=='/'?n1/n2:(c=='*'?n1*n2:(c=='+'?n1+n2:(c=='-'?n1-n2:0)))));
      }
      public static void main(String ar[])throws java.io.IOException
      {
      char c[]={'%','/','*','+','-'};
      String expression=getString();
      for(int i=0;i<c.length;i++)
      {
      java.util.ArrayList al=new java.util.ArrayList(split(expression));
      String temp[]=new String[al.size()];
      int zip=0;
      for(String s:al)
      {
      temp[zip++]=String.valueOf(s);
      }
      for(int j=0;j<temp.length;j++)
      {
      if(temp[j].equals(""+c[i]))
      {
      zip=sum(Integer.parseInt(temp[j-1]),Integer.parseInt(temp[j+1]),c[i]);
      temp[j-1]=null;
      temp[j]=null;
      temp[j+1]=String.valueOf(zip);
      }
      }
      expression="";
      for(int j=0;j<temp.length;j++)
      {
      if(temp[j]!=null)
      expression+=temp[j];
      }
      zip=0;
      for(int x=0;x<expression.length();x++)
      {
      if(expression.charAt(x)=='%'||expression.charAt(x)=='/'||expression.charAt(x)=='*'||expression.charAt(x)=='+'||expression.charAt(x)=='-')
      zip++;
      }
      if(zip==0)
      break;
      }
      System.out.print("ANSWER:"+expression);
      }
      }

Leave a Reply

Your email address will not be published. Required fields are marked *