Java 堆栈不为空,但引发空堆栈异常
这是Swing类中的一个助手方法。我正在编写一个程序,根据树木的数量和高度,计算猴子可以在其中摇摆的可能的成对树木Java 堆栈不为空,但引发空堆栈异常,java,exception,stack,is-empty,peek,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
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;
}
}
随后,else条件运行:
else{
while(currTree>s1.peek()){
s1.pop();
count++;
}
if(!s1.isEmpty()){
count++;
}
if(currTree==s1.peek()){
s1.pop();
}
s1.push(currTree);
}
代码成功推入第一个整数后,它将在第行为s1.peek()方法抛出EmptyStackException
while(currTree>s1.peek())
为什么会这样?我的意思是我已经检查过了,当第二次迭代运行时,s1不是空的。您的循环可能会删除
堆栈的所有元素,此时堆栈将变为空,s1.peek()
将抛出异常
为了防止这种情况发生,请在循环中添加一个条件:
while(!s1.isEmpty() && currTree>s1.peek()) {
s1.pop();
count++;
}
移除s1.pop()中的对象代码>,因此在上一次迭代中,s1
为空。您需要在peek()
之前检查s1
是否为空。改为
while(!s1.isEmpty() && currTree > s1.peek()) {
s1.pop();
count++;
}
while(!s1.isEmpty() && currTree > s1.peek()) {
s1.pop();
count++;
}