Java Lesson 23: Print whole stack

From Erlands Wiki

Jump to: navigation, search

The main program looks like this:

import java.util.Stack;
import java.util.EmptyStackException;
 
public class MyClass {
    public static void main(String[] args) {
        Stack stack = new Stack();
        for(int i=0;i<args.length;i++) {
            stack.push(args[i]);
        }
        print(stack);
    }
 
    /**
     * Pops an element from the stack and
     * Returns the element if the stack is not empty
     * Returns null if the stack is empty
     */
    private static Object popFromStack(Stack stack) {
        try {
            return stack.pop();
        }catch(EmptyStackException e){
            return null;
        }
    }
}

The program is executed as:

java MyClass 5 blue Hello

The output should be the specified parameters in reverse order like:

You specified: Hello
You specified: blue
You specified: 5

Your work it to create the print method.

An optional exercise is to modify the print method so it prints the parameters in correct order instead of reverse order.

Personal tools