Turn a String into a Math Expression? [duplicate]

2020-01-31 08:12发布

问题:

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.

回答1:

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.



回答2:

Let me state is as an answer a process which could be adopted as I think though browsing over a couple of questions on SO you should get a fair idea on how to do this without loading a JS compiler.

For starters you need to parse your string through a function that converts your math string to a infix string. Then this you basically evaluate this expression as another function by breaking down the string in a loop to return your answer. A beautifully detailed process can be found here.