Navin a.s
Navin a.s

Reputation: 416

Pop elements in stack until some element

I have a code like this:

public static void main(String[] args) throws Exception {
    String popElement ;
   Stack<String> stack = new Stack();
   stack.push( "new" );
   stack.push( "new" );
   stack.push( "new1" );
   stack.push( "new2" );
   if(! stack.empty() )
   {
       do
       {
           popElement = stack.pop();
           System.out.println( "pop element "+popElement );
       }while (popElement.equals( "new" ));
   }
   System.out.println( "STACK :"+stack );

I want to pop stack until new, I need stack output as [new,new].. But my code pops only new2, it shows output as [new,new,new1. I need only [new,new]].

Upvotes: 1

Views: 1809

Answers (1)

janos
janos

Reputation: 124656

In other words, too many elements are popped. To check that the next element is not "new", without actually removing that element, you need to use peek() instead of pop().

Also, to avoid crashing the program in case all the elements are "new", you need to repeatedly check that the stack is not empty.

while (!stack.empty() && !stack.peek().equals("new")) {
    System.out.println("pop element " + stack.pop());
}
System.out.println("STACK :" + stack);

Upvotes: 3

Related Questions