-3

How to input a string such as : "1+2/3*2" To give the output as 2.333

Basically I want to input a string which is a mathematical equation and output the answer using BODMAS . I've tried breaking the string into an array of operands and an array of operators in the same order but I'm unable to do the BODMAS part.

3 Answers3

0

you can use stack to evaluate the expression, use Dijkstra's twostack algorithm.

public class DijkstraTwoStack {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String exp[] = scanner.nextLine().split(" ");
        Stack<String> ops = new Stack<String>();
        Stack<Double> vals = new Stack<Double>();

        for(int i = 0; i < exp.length; i++) {
                        String s = exp[i];
            if (s.equals("(")) {
            }
            else if (s.equals("+") || s.equals("*")) {
                ops.push(s);
            } else if (s.equals(")")) {
                getComp(ops, vals);
            } else {
                vals.push(Double.parseDouble(s));
            }
        }
        getComp(ops, vals);
        System.out.println(vals.pop());
    }

    private static void getComp(Stack<String> ops, Stack<Double> vals) {
        String op = ops.pop();
        if (op.equals("+")) {
            vals.push(vals.pop() + vals.pop());
        } else if (op.equals("*")) {
            vals.push(vals.pop() * vals.pop());
        }
    }
}
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
Rohit Kumar
  • 311
  • 1
  • 3
  • 3
0

This sounds like a homework problem but nevertheless. Breaking it down into operands and operators is a good start. But you'll need to keep a good record of their position in the equation. Next step would be iterate through your BOMDAS to do each step separately.

So search through your operands if you see a bracket do that part of the equation first, however note with brackets this will need to start the BOMDAS evaluation all over again. So maybe implement it in a recursive function could be powerful. Next search through for a multiplication. If you find one multiple the two operatands on either side. This will result in a new operand between the existing two operators.

Continue iterating through each element of the BOMDAS ensuring when performing an operation the new operand is put in place of the existing two operands and operator.

0

There are two ways to do it, Use the Javascript engine - Evaluating a math expression given in string form or the BeanShell interpreter How to parse a mathematical expression given as a string and return a number?

Community
  • 1
  • 1
Jerin Joseph
  • 1,087
  • 9
  • 17