0

i can't figure out why this part of my program won't work, I peek outside the while loop and confirm that the stack is not empty, yet when i try to access it inside the while loop I get this error:

"Exception in thread "main" java.util.EmptyStackException at java.util.Stack.peek(Unknown Source)"

here's the relevant piece of code

String test = list.peek();
    System.out.println(test);
    while(list.peek() != null)
    {
        temp = list.pop();

There's more too the while loop but it breaks once list.peek is called inside the parenthesis, I tried changing it to "while(test != null)" for test purposes but it breaks once it gets to list.pop()

4

2 回答 2

2

The peek method throws an EmptyStackException if the stack is empty. To test if the stack is empty, use the empty() method:

while(!list.empty())

Also, don't name your Stack "list"; that can be confusing.

于 2013-03-18T21:43:33.770 回答
2

When you peek(), that can also return a EmptyStackException. You should use this code instead:

while(!list.empty()) {
    temp = list.pop();
}  

What's happening is that peek can't deal with an empty element the way you are assuming it can. You have to make sure the stack isn't empty before you peek().

As a side note, it's a bit odd to name your Stack 'list'. That would imply your structure is a List

于 2013-03-18T21:44:18.593 回答