堆栈不为空但抛出空堆栈异常

时间:2016-03-21 07:57:17

标签: java exception stack is-empty peek

这是我的Swing类中的一个帮助方法。我正在编写一个程序来计算猴子可以在它们之间摆动的树对,给定树木的数量和它们的高度。

public class Swing {

 private long processSwing(int N, Scanner sc){
  int i=0;
  long count=0;
  Stack<Integer> s1 = new Stack<>();
  while(i<N){//scanning loop
   int currTree=sc.nextInt();
   if(s1.isEmpty()){//if s1 is empty(only will happen at the first tree, because consequently s1 will always be filled)
    s1.push(currTree);//push in first tree
   }
   else{
    while(currTree>s1.peek()){//this loop removes all the previous trees which are smaller height, and adds them into pair counts
     s1.pop();
     count++;
    }
    if(!s1.isEmpty()){//if the stack isnt empty after that, that means there is one tree at the start which is same height or bigger. add one pair.
     count++;
    }
    if(currTree==s1.peek()){
     s1.pop();
    }
    s1.push(currTree);// all trees will always be pushed once. This is to ensure that the stack will never be empty.
   }//and the tree at the lowest stack at the end of every iteration will be the tallest one
   i++;
  }
  return count;
 }
}

这部分确保如果堆栈s1为空,它将推入我扫描到堆栈中的第一个整数。

if(s1.isEmpty()){
     s1.push(currTree);//push in first tree
}

随后,else条件运行:

 else{
    while(currTree>s1.peek()){
     s1.pop();
     count++;
    }
    if(!s1.isEmpty()){
     count++;
    }
    if(currTree==s1.peek()){
     s1.pop();
    }
    s1.push(currTree);
    }

代码成功推送第一个整数后,它会抛出一个EmptyStackException,对于行的s1.peek()方法

 while(currTree>s1.peek())

为什么会这样?我的意思是我已经检查过,当第二次迭代运行时,s1并不是空的。

2 个答案:

答案 0 :(得分:0)

您的循环可能会删除Stack的所有元素,此时Stack将变为空,s1.peek()将抛出异常。

为了防止这种情况发生,请在循环中添加一个条件:

while(!s1.isEmpty() && currTree>s1.peek()) {
  s1.pop();
  count++;
}

答案 1 :(得分:0)

您删除If .Value = sheets("JAN!")中的对象,因此在上一次迭代中s1.pop();为空。您需要检查s1之前s1是否为空。改为

peek()