Results 1 to 3 of 3
  1. #1
    bugger is offline Senior Member
    Join Date
    Nov 2007
    Posts
    111
    Rep Power
    0

    Default Stack not popping

    The code below should pop 4 elements, but it just shows 2 elements. I am not able to understand the prolem there:
    Java Code:
    		Stack stack = new Stack();
    		stack.push("Obj1");
    		stack.push("Obj2");
    		stack.push("Obj3");
    		stack.push("Obj4");
    		
    		System.out.println(stack.size());
    		
    		for(int i=0;i<stack.size();i++)
    		{
    			System.out.println("Stack header is: " + stack.peek());
    			System.out.println("Popped value is: " + stack.pop());
    		}
    Output:

    Java Code:
    Stack header is: Obj4
    Popped value is: Obj4
    Stack header is: Obj3
    Popped value is: Obj3

  2. #2
    jelly's Avatar
    jelly is offline Member
    Join Date
    Jan 2008
    Location
    Somerset, UK
    Posts
    46
    Rep Power
    0

    Default

    Your problem is caused by

    Java Code:
    for(int i=0;i<stack.size();i++)
    you are getting the size of the stack each time round but your index is increasing in value while the stack size is decreasing so:

    loop 1, i = 0, stack.size() = 4, you print values
    loop 2, i = 1, stack.size() = 3, you print values
    loop 3, i = 2, stack.size() = 2, and you drop out of the loop

    take the original stack size first and then use that for the loop check, i.e.

    Java Code:
    int original_stack_size = stack.size();
    for(int i=0; i< original_stack_size; i++)
    as well as fixing the problem it is also more efficient
    -- Hope that helps

  3. #3
    bugger is offline Senior Member
    Join Date
    Nov 2007
    Posts
    111
    Rep Power
    0

Similar Threads

  1. Implementing a Stack Using two Queues
    By rhm54 in forum New To Java
    Replies: 3
    Last Post: 12-01-2010, 10:28 AM
  2. Making a stack from a LinkedList
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 10:28 PM
  3. Stack Trace
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-10-2007, 05:29 PM
  4. Help with heap and stack
    By coco in forum Advanced Java
    Replies: 1
    Last Post: 08-06-2007, 02:21 PM
  5. Creating a stack with data
    By ai_2007 in forum Advanced Java
    Replies: 2
    Last Post: 07-02-2007, 03:28 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •