0

所以这是我的代码:

public double evaluate(){

        Stack numbers = new Stack();
        Stack operators = new Stack();


        String[] divert = {};
        String problem = "2 + 2 + 3";

        divert = problem.split(" ");

        for(int i = 0; i < divert.length; i++){


            if(divert[i].equals("*") || divert[i].equals("/")|| divert[i].equals("+") || divert[i].equals("-")){
                if(operators.peek().equals("*") || operators.peek().equals("/")){
                    int a = Integer.parseInt((String)numbers.pop());
                    int b = Integer.parseInt((String)numbers.pop());
                    String operand = (String)operators.pop();
                    numbers.push(doMath(b, operand, a));

                }
                else if ( divert[i].equals("+") || divert[i].equals("-")){
                    operators.push(divert[i]);
                }

            } else {
                numbers.push(divert[i]);
            }
        }

        while(!operators.empty()){
            int a = Integer.parseInt((String)numbers.pop());
            int b = Integer.parseInt((String)numbers.pop());
            String operand = (String)operators.pop();
            numbers.push(doMath(a, operand, b));
        }
        double endNumber = (double)numbers.pop();
        return endNumber;
    }

我不断收到奇怪的错误,一个告诉我嵌套 if 语句中的 if(operators.peek().equals... 位返回 EmptyStackException。我在尝试将弹出的数字 (endNumber) 强制转换为返回时遇到另一个错误它。我在将其转换为双精度时遇到了问题。

如果有人会看到这个并告诉我问题是什么以及解决问题的任何可能方法,那就太好了,因为我真的不明白为什么它会给我这些错误。

我知道删除 divert[i].equals("+")/("-") 消除了第一个错误的问题,但这对我正在做的事情不太有利。

4

1 回答 1

1

对于双打的问题,请使用 Stack 的泛型功能

Stack<Double> numbers = new Stack<Double>();

这将确保只有 Doubles 存储在堆栈中。自动拆箱(将双打转换为双打,反之亦然)功能意味着您应该能够做到

double x = 5.0;
numbers.push(x);
double y = numbers.pop();

对于良好的形式也使用

Stack<String> operator;

用于测试操作员堆栈使用

if( !operators.empty() && (operators.peek().equals("*") || operators.peek().equals("/")) )

即在偷看之前测试堆栈是否不为空。

还要检查你从堆栈中弹出数字的顺序,在最后的代码中。我感觉你会遇到“5 - 3”的问题。

此外,您总是想推动当前的运营商。看起来“*”或“/”永远不会被推送。

于 2014-04-18T07:08:42.220 回答