# Calculator which follows BODMAS rules in Java

Today we’ll implement a calculator that follows BODMAS rule in 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

Implementing this code requires importing java.util.Stack.

• We’ll be pushing our elements into the stack,
• Parsing 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
• Rest of the stack contains the remaining tokens
• Evaluation of remaining tokens takes place
• We’ll be repeating this procedure until the result reaches the top of the stack.
```import java.util.Stack;

public class B_C
{
public static int solve_this(String expression)
{
char[] ar_tok = expression.toCharArray();

// This is the Stack for numbers, our values
Stack<Integer> values = new Stack<Integer>();
// This Stack is for our Operators called 'sta_obj'
Stack<Character> sta_obj = new Stack<Character>();

for (int i = 0; i < ar_tok.length; i++){
// Our present token is a whitespace? so skip it
if (ar_tok[i] == ' ')
continue;
// Our token is a number? push it onto the stack for numbers
if (ar_tok[i] >= '0' && ar_tok[i] <= '9')
{
StringBuffer buff_s = new StringBuffer();
// Incase the number has more than one digit
while (i < ar_tok.length && ar_tok[i] >= '0' && ar_tok[i] <= '9')
buff_s.append(ar_tok[i++]);
values.push(Integer.parseInt(buff_s.toString()));
}

// Our token is an opening bracket? push it onto 'sta_obj'
else if (ar_tok[i] == '(')
sta_obj.push(ar_tok[i]);

// Once we meet the closing bracket , solve the complete bracket
else if (ar_tok[i] == ')') {
while (sta_obj.peek() != '(')
values.push(applyOp(sta_obj.pop(), values.pop(), values.pop()));
sta_obj.pop();
}
// Incase the token is an operator
else if (ar_tok[i] == '+' || ar_tok[i] == '-' ||
ar_tok[i] == '*' || ar_tok[i] == '/')
{
// While top of 'sta_obj' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'sta_obj'
// to bring on top two elements in the values stack.
while (!sta_obj.empty() && hasPrecedence(ar_tok[i], sta_obj.peek()))
values.push(applyOp(sta_obj.pop(), values.pop(), values.pop()));

// Pushing the token onto 'sta_obj'.
sta_obj.push(ar_tok[i]); }}

// Now that the expression is parsed, we'll use the rest of
/ sta_obj for the remaining values
while (!sta_obj.empty())
values.push(applyOp(sta_obj.pop(), values.pop(), values.pop()));

// If the top of 'values' has the result, simply return it
return values.pop();}
// True is returned if 'oper_2' has higher or same precedence as 'oper_1',
// else false is returned
public static boolean hasPrecedence(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;}
// Here's a utility method for applying an operator 'oper' on the operands 'var1' and 'var2'
public static int applyOp(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.. immpossible!");
return var1 / var2;
}
return 0;}

// Main section
public static void main(String[] args)
{
System.out.println("******OUTPUTS******");
System.out.println(BOD_Calc.solve_this("50 + 5 * (70/70)"));
System.out.println(BOD_Calc.solve_this("50 + 5 * 70/70"));
System.out.println(BOD_Calc.solve_this("100 + 5 * 30"));
System.out.println(BOD_Calc.solve_this("100 * ( 5 + 30 ) "));
System.out.println(BOD_Calc.solve_this("100 / 0"));
}```

#### Explanation

In the above code, B_C is the main Class. It has the following methods:

• int solve_it()
• boolean hasPrecedence()
• int calc_Op()
• Main()

Likewise, int solve_it() basically brings everything to a character array, to parse the expression. Here ar_tok is the character array storing the parse tokens. For pushing numbers onto stack we have ‘val_sta’ , and for pushing operators onto stack we have ‘sta_obj’. After the declaration of variables, we move to the parsing of the expression. Parsing the expression requires StringBuffer class,  with its instance ‘buff_s’.

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

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

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

#### Output

The sample code snippet produces the following output:

```******OUTPUTS******
50
4905
250
3500
Exception in thread "main" java.lang.ArithmeticException: division by zero.. immpossible!```

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

How Java objects are stored in memory

### One response 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

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);