Below is just one little chunk of my code, I am trying to understand why if I add in the line of code that is commented out it throws an EmptyStackException. I need to add the item at the top of oneStack to the top of twoStack if there are two null values in a row (generated by calling items.getNextItem()). Any insight into why this breaks? Or how I can get the top value of oneStack to also be the top value of twoStack at that point?
I have tried putting that line of code in an if, assigning a variable for the value of oneStack.peek(), but none of that has helped either. It is almost as if that one commented out line is emptying the whole stack (??).
Main point: if in that commented out line of code I swap oneStack.peek() with any other value, it works just fine. So why does it not work with oneStack.peek()?
oneStack.push(firstItem);
twoStack.push(firstItem);
nextItem = items.getNextItem();
oneStack.push(nextItem);
twoStack.push(nextItem);
while (!done) {
if (oneStack.peek() == null) {
oneStack.pop();
oneStack.pop();
twoStack.pop();
twoStack.push(oneStack.peek()); // the commented out line below causes this line to throw an EmptyStackException if uncommented.
newItem = items.getNextItem();
oneStack.push(nextItem);
if (oneStack.peek() == null) {
oneStack.pop();
twoStack.pop();
//twoStack.push(oneStack.peek()); // if I uncomment this it breaks, but this needs to happen for twoStack to be correct
} else {
twoStack.push(nextItem);
}
} else if (oneStack.peek() == targetItem) {
done = true;
} else {
nextItem = items.getNextItem();
oneStack.push(nextItem);
twoStack.push(nextItem);
}
This is the way that items are being generated:
item1, item2, item3, item4, item5, null, null, item6, item7
In the end, this is what is left of the stacks: oneStack: item1, item2, item6, item7
twoStack: item1, item2, item3, item4, item5, item4, item6, item7 (item3 is missing)
twoStack should be: item1, item2, item3, item4, item5, item4, item3, item6, item7