BODMAS program in Java

In this short post, I will be sharing the BODMAS program in Java. BODMAS stands for Bracket of Division Multiplication Addition Subtraction. BODMAS is used for calculating arithmetic calculations or expressions. Following this order, we can achieve correct arithmetic outputs or results.

Read Also: Dice Roll Game Source Code in Java

Let's dive deep into the topic:

BODMAS program in Java

Follow the below steps for BODMAS implementation in Java:
1. Convert the given expression into a character array.
2. Iterate through the character array:
    a. continue if the element in the array is whitespace
    b. If the element is a number then push it into the stack
3. Parsing the given expression to identify the tokens
4. If we encounter brackets, the highest priority is given to its enclosing expression.
5. Evaluating of remaining tokens takes place
6. We will be repeating the above steps till we reach the top of the stack.


 import java.util.Stack;

public class BODMAS {
    public static void main(String args[]) 
    {
        System.out.println("******Expression Outputs******");
        System.out.println(BODMAS.solveExpression("30 + 3 * (60/60)")); 
        System.out.println(BODMAS.solveExpression("90 + 7 * 50/50")); 
        System.out.println(BODMAS.solveExpression("100 + 3 * 50")); 
        System.out.println(BODMAS.solveExpression("1000 * ( 1 + 70 ) "));
        System.out.println(BODMAS.solveExpression("1000 / 0"));
    }
    public static int solveExpression(String expression)
    {
        char[] tokens = expression.toCharArray();
        Stack<Integer> values = new Stack<>();
        Stack<Character> operators = new Stack<>();
        for(int i=0; i < tokens.length; i++)
        {
            if(tokens[i] == ' ')
                continue;
            if (tokens[i] >= '0' && tokens[i] <= '9') 
            { 
                StringBuilder str = new StringBuilder();
                while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
                {
                    str.append(tokens[i++]);
                }
                values.push(Integer.parseInt(str.toString())); 
            }
            else if (tokens[i] == '(') 
                operators.push(tokens[i]);
            else if (tokens[i] == ')') { 
                while (operators.peek() != '(') 
                {
                    values.push(applyOperation(operators.pop(), values.pop(), values.pop())); 
                }
                operators.pop();
            }
            else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/')
            {
                while (!operators.empty() && hasPrecedence(tokens[i], operators.peek())) 
                {
                    values.push(applyOperation(operators.pop(), values.pop(), values.pop()));
                }
                operators.push(tokens[i]);    
            }
        }
        while (!operators.empty()) 
        {
            values.push(applyOperation(operators.pop(), values.pop(), values.pop())); 
        }
        return values.pop();
    } 

    public static boolean hasPrecedence(char oper1, char oper2)
    { 
        if (oper2 == '(' || oper2 == ')') 
            return false; 
        if ((oper1 == '/' || oper1 == '*') && (oper2 == '+' || oper2 == '-')) 
            return false; 
        else
            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;
    }
  }
    


Output:
******Expression Outputs******
30
2507
250
71000

Exception in thread "main" java.lang.ArithmeticException: division by zero not possible!


That's all for today. Please mention in the comments if you have any questions related to BODMAS program in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry