Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn a String into a Math Expression? [duplicate]

Tags:

java

math

parsing

Lets say I have a method that's declared this way:

public double Calc(String expression) {

// Code

}

I want to take a String expression like

"2 + 4 - (3 * 4)"

Then feed it to Calc() and it should return the value that it gets.

Can you Parse a Math Expression out of a String so that it becomes an expression that Java can understand? Because normally you could just write

return 2 + 4 - (3 * 4);

But that would only work for that single expression.

like image 903
OmniOwl Avatar asked Feb 26 '13 09:02

OmniOwl


1 Answers

I would suggest using Dijkstra's twostack algorithm.

This should be pretty much what you need:

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

Haven't tested it, but it should be about right.

like image 124
Jeroen Vannevel Avatar answered Oct 13 '22 10:10

Jeroen Vannevel