将字符串转换为数学表达式? [英] Turn a String into a Math Expression?

查看:96
本文介绍了将字符串转换为数学表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个声明这种方式的方法:

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

然后将其提供给 Calc(),它应该返回它得到的值。

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

你能从字符串中解析数学表达式,以便它成为Java可以理解的表达式吗?因为通常你可以写

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.

推荐答案

我建议使用Dijkstra的twostack算法。

I would suggest using 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());
        }
    }
}

尚未测试过,但它应该是正确的。

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

这篇关于将字符串转换为数学表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆