Java中的方程求解器 - 未将值压入堆栈

时间:2012-09-04 10:25:12

标签: java

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

我遇到的问题是它崩溃告诉我列表是空的(此时: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;
}

1 个答案:

答案 0 :(得分: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在其评论中所建议的那样),您可以确定这是否是您问题的根本原因。