This is my first time working with stacks. I am trying to get familiar with using some of the methods from java.util.Stack. Specifically i am trying to set the size of the stack and then, using a for loop, push items onto the stack until the stack has reached its capacity. However I seem to be having some trouble,
sometimes my output looks like [null,null,null... 0,2,4...] depending on the size, and sometimes (when I change the code to try something else) I just get
[null,null,null,......]. What I would like to do is populate the stack with numbers [1- whatever the size of the stack is], then on the next iteration of the loop I want it to reach and print that the stack is full.
Code:import java.util.Stack; public class myStack{ private static Stack stack = new Stack(); public static void main(String[] args) { stack.setSize(5); //System.out.println(stack.size()); //System.out.println(stack.empty()); for(int i= 0; i<stack.size(); i++){ if(!stack.isEmpty()){ stack.push(i); } else{ System.out.println("stack is full"); } i+=1; } System.out.println(stack); } }
Just a tip, inside your for loop, you call stack.size() each time you iterate through that loop which makes your program slightly less efficient.
Now onto programming theory. Stacks are implemented where you can either pop or push an element to/from the stack. By setting the size, you are making 5 null pointers in the stack because it pushes 5 nulls down on. Here is what you really need:
Code:import java.util.Stack; public class main{ private static Stack stack = new Stack(); public static void main(String[] args) { int size = 5; //System.out.println(stack.size()); //System.out.println(stack.empty()); for(int i= 0; i<size; i++){ stack.push(i); } System.out.println(stack); } }
Thank you, that was so simple. Sometimes I tend to overlook the obvious.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks