1

可能重复:
评估以字符串形式给出的数学表达式

我需要一些帮助来完成我们的任务。我试图创建一个将使用运算符优先级进行计算的程序。如果可能的话,我想计算一个数组列表中的表达式。例如。[4+2x2-3] 应该首先计算 2x2,所以结果将是 [4+4-3] 等等......我的程序只计算第一个操作,但不能通过其他操作重复。也..它只计算最高优先级的运算符何时开始。前任。[2^1-2] 变为 [2-2]。但是当 [2-1^2] 它什么也没做。谢谢帮助

List<String> subroutine = new CopyOnWriteArrayList<String>(input);
        for(String i : subroutine)
    {
        switch(currentstate)
        {
            case q0:
                if(isDigit(i))
                {
                    currentstate = q1;
                }
            break;

            case q1:
                if(i.equals("^"))
                {
                    maxPriority = i;
                    int index = subroutine.indexOf(maxPriority);
                    int num1 = Integer.parseInt(subroutine.get(index-1));
                    int num2 = Integer.parseInt(subroutine.get(index+1));
                    int total = (int) Math.pow(num1, num2);

                    String stringTotal = Integer.toString(total);
                    String addToExp = subroutine.set(index, stringTotal);
                    int indexAddToExp = subroutine.indexOf(stringTotal);
                    subroutine.remove(indexAddToExp+1);
                    subroutine.remove(indexAddToExp-1);
                    System.out.println(subroutine);
                }
                else if( (i.equals("x") || i.equals("/")) && (!input.contains("^")) )
                {
                    if(i.equals("x"))
                    {
                        maxPriority = i;
                        int index = subroutine.indexOf(maxPriority);
                        int num1 = Integer.parseInt(subroutine.get(index-1));
                        int num2 = Integer.parseInt(subroutine.get(index+1));
                        int total = num1 * num2;

                        String stringTotal = Integer.toString(total);
                        String addToExp = subroutine.set(index, stringTotal);
                        int indexAddToExp = subroutine.indexOf(stringTotal);
                        subroutine.remove(indexAddToExp+1);
                        subroutine.remove(indexAddToExp-1);
                    }
4

1 回答 1

4

您应该考虑构建一个比简单地使用字符串集合更复杂的表达式结构。

基本上,您将希望根据给定的上下文无关语法将给定的算术表达式解析为抽象语法树,大致如下所示:

ArithmethicExpression := CompoundExpression | LiteralExpresion
LiteralExpression := {0-9}+ (meaning at least one digit)
CompoundExpression := LiteralExpression FunctionExpression LiteralExpression

这个语法只是你需要的一个粗略的概念,但它肯定会帮助你更容易地实现你需要的东西。

这里还有一个问题,显然是相关的。特别是这个答案对你来说真的很有趣。

于 2012-10-12T12:11:25.997 回答