Reputation: 153
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()
Upvotes: 1
Views: 12433
Reputation: 3402
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
Upvotes: 3