Это вспомогательный метод в моем классе 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{
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 не пуст, когда выполняется вторая итерация.
Большое спасибо! :) –
@DerianTungka Добро пожаловать – Eran