//StackTest.java //1.generate user-specified number of random ints, push each onto stack, then pop them all off. //2.loop: randomly push or pop a random int once per second until user wants to stop. //Stack is one of the built-in classes of the Java Collections Framework. // It is a list that is only accessed at one end, called the "top"... // Methods: // push(object) onto top of stack // pop() remove and return object at top of stack // peek() return but don't remove top // empty() return true if stack is empty // more... but the push, pop, empty are the definition of a pure stack // http://java.sun.com/j2se/1.5.0/docs/api/java/util/Stack.html //Stack is a subclass of Vector, which is almost the same as an ArrayList, //so Stack has add, remove, get, iterator etc methods but they usually //wouldn't be used. //LinkedList can be used as a stack. Either its addFirst()/removeFirst() or //addLast()/removeLast() methods could be used as push and pop. import java.util.*; import javax.swing.*; class StackTest { public static void main(String[] args) { String input, userstring; int size; int range; int userAnswer; int randInt; Stack myStack = new Stack(); //**create empty stack input = JOptionPane.showInputDialog( "Enter number of random ints to generate" ); size = Integer.parseInt( input ); input = JOptionPane.showInputDialog( "Enter upper range of the random ints" ); range = Integer.parseInt( input ); System.out.println("Now pushing items onto the stack."); printStack(myStack); //display stack at each step for (int i=1; i<=size; i++) { randInt = (int)(Math.random()*range); myStack.push(new Integer(randInt)); //***** printStack(myStack); //display stack at each step } System.out.println(); System.out.println("Now popping the items off the stack."); printStack(myStack); //display stack at each step while (!myStack.empty()) { System.out.print("popped off: " + myStack.pop() + "\n"); //***** printStack(myStack); //display stack at each step } System.out.println(); userAnswer = JOptionPane.showConfirmDialog(null, "Do you want to do random pushes and pops?", "", JOptionPane.YES_NO_OPTION); if (userAnswer == JOptionPane.YES_OPTION) { while (true) { if (Math.random() < .5) { //push a new random int object randInt = (int)(Math.random()*range); System.out.println("pushing: " + randInt); myStack.push(new Integer(randInt)); } else //pop if (!myStack.empty()) //check stack is not empty System.out.println("popped off: " + myStack.pop()); else System.out.println("underflow"); //stack is empty, nothing to pop printStack( myStack ); //slow it down try { Thread.sleep(1000); //1000 ms pause } catch (InterruptedException e) { } } } System.exit(0); } static void printStack( Stack s) { System.out.print("Stack is: "); //don't normally iterate over a stack. here for illustration purposes. Iterator items = s.iterator(); while (items.hasNext()) System.out.print(items.next()+" "); System.out.println(); } }