Java stack examples: a solution


import java.util.Stack;
import java.util.Random;

public class TestStack {
        public static void main(String [] args){
                // create a new stack of strings
                Stack<String> stack = new Stack<String>();

                // push some strings onto the stack
                stack.push("apple");
                stack.push("banana");
                stack.push("kiwi");

                // Java allows you to print the entire stack
                System.out.println(stack);

                System.out.println(stack.empty());

                // pop the stack until it becomes empty
                while (!stack.empty()) {
                        System.out.println(stack.pop());
                }

                // create a new stack of integers
                Stack<Integer> stackInt = new Stack<Integer>();
                stackInt.push(1);

                // peek at the top element, but keep it on the stack
                System.out.println(stackInt.peek());

                // the stack is not empty
                System.out.println(stackInt.empty());

                // empty the stack
                int n = stackInt.pop();

                System.out.println(n);

                System.out.println(stackInt.empty());

                // write a loop to store 100 random elements on the stack
                // the random elements are between 1 and 10 inclusive
                Random r = new Random();
                for(int i = 0; i <100; i++){
                        stackInt.push(r.nextInt(10) + 1);
                }
                System.out.println(stackInt);
                lessThanSix(stackInt);
                System.out.println(stackInt);
        }

        // write a method to remove all elements from the stack that
        // are > 5. Do not change the order of the remaining elements.
        public static void lessThanSix(Stack<Integer> stack) {
                Stack<Integer> tempStack = new Stack<Integer>();
                while(!stack.empty()){
                        tempStack.push(stack.pop());
                }
                while (!tempStack.empty()){
                        int element = tempStack.pop();
                        if (element < 6) {
                                stack.push(element);
                        }
                }
                System.out.println(tempStack);
        }
}

CSci 2101 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.