This is a helper method in my Swing class. I am writing a program that calculates the possible pairs of tree that monkeys can swing between, given the number of trees and their height.
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;
}
}
This portion ensures that if the stack s1 is empty, it will push in the very first integer i have scanned into the stack.
if(s1.isEmpty()){
s1.push(currTree);//push in first tree
}
Subsequently, the else condition runs:
else{
while(currTree>s1.peek()){
s1.pop();
count++;
}
if(!s1.isEmpty()){
count++;
}
if(currTree==s1.peek()){
s1.pop();
}
s1.push(currTree);
}
After the code successfully pushes in the first integer, it will throw an EmptyStackException, for s1.peek() method at the line
while(currTree>s1.peek())
Why is this so? I mean i've checked and s1 isn't empty when the 2nd iteration runs.