Assuming a user input a number of website url ranging from 1-10 into a stack and next has to input the number of times he/she clicks the back button in order to pop the website url out from the stack. How do I display the stack as empty once the website url has all been popped out from the stack if the user clicks the back button more than the number of website url he/she entered?
Right now, my coding just display all the "pop" urls as empty instead of showing the rest of the "pop" urls. This is what I needed for the outcome.
Number of times back button is clicked: 6
#1 click: http://www.twitter.com #2 click: http://www.facebook.com #3 click: http://www.youtube.com #4 click: http://www.google.com.sg #5 click: Empty
#6 click: Empty
For the purposes of this loop, website and backbutton are fixed values. Only j and the state of myStack change as the loop progresses. So the expression website==backbutton gives the same result in each loop iteration.
If I were trying to solve this problem, I wouldn't use website or backbutton in the if statement. Instead, I would do a check to see if there are still any items left in the stack. Is there a method of the Stack class that returns true if the stack is empty, false otherwise?
Don't use java.util.Stack. Use this instead. Use the four methods you are used to from other stacks, viz push pop peek and there is one other whose name I am pretending to have forgotten. There is also a size method which allows you to see how many elements there are. Note that the two classes differ slightly in their Exception handling.
You will find your coding much easier if you get it out of the main method. Pushing popping and displaying should be done by separate methods.