-1

我遇到了方程求解器的一部分问题。我有一个包含后缀方程的对象数组,并且此方法评估每个值。

我遇到的问题是它崩溃告诉我列表为空(此时:double num1 = ((double)operandStack.pop());)

有人可以告诉我我在这里做错了什么吗?

    DSAQueue<Object> postfixQueue = new DSAQueue<Object>();
.
.
.
.


private double evaluatePostfix (Queue<Object> postfixQueue)
{

DSAStack<Double> operandStack = new Stack<Double>();
while (postfixQueue.isEmpty() == false)
    {
    if (postfixQueue.peek() instanceof Double)
        {
        operandStack.push((Double)(postfixQueue.dequeue()));
        }
    else
        {
        double num1 = ((double)operandStack.pop());
        double num2 = ((double)operandStack.pop());
        char operator = ((char)postfixQueue.dequeue());
        double result = executeOperation (operator, num1, num2);
        operandStack.push(result);
        }
    }
double solution = operandStack.top();
return solution;
}
4

1 回答 1

2

请参阅下面代码中的注释。似乎有一个简单的代码路径会导致错误:

DSAQueue<Object> postfixQueue = new DSAQueue<Object>();

private double evaluatePostfix (Queue<Object> postfixQueue)
{

  // Here you define an empty list
  DSAStack<Double> operandStack = new Stack<Double>();

  while (postfixQueue.isEmpty() == false)
  {
    if (postfixQueue.peek() instanceof Double)
    {
      operandStack.push((Double)(postfixQueue.dequeue()));
    }
    else
    {
      // If the first item in postfixQueue was not a Double, you're now
      // pop-ing from an empty stack
      double num1 = ((double)operandStack.pop());
      double num2 = ((double)operandStack.pop());
      char operator = ((char)postfixQueue.dequeue());
      double result = executeOperation (operator, num1, num2);
      operandStack.push(result);
    }
  }
  double solution = operandStack.top();
  return solution;
}

如果您使用调试器逐步完成(如 Peter 在他的评论中所建议的那样),您可以确定这是否是问题的根本原因。

于 2012-09-04T10:33:45.423 回答