2016-03-21 3 views
0

Это вспомогательный метод в моем классе 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 не пуст, когда выполняется вторая итерация.

ответ

0

Ваша петля может удалить все элементы Stack, после чего Stack станет пустым, а s1.peek() выдаст исключение.

Для того, чтобы не допустить этого, добавьте условие к вашей петле:

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

Большое спасибо! :) –

+0

@DerianTungka Добро пожаловать – Eran

0

Вы удаляете объект в s1.pop();, поэтому в последней итерации s1 пуст. Вам необходимо проверить, что s1 не пуст до peek(). Изменение на

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

Спасибо большое! :) –

Смежные вопросы