Java Lesson 22: First parameter from stack

From Erlands Wiki

Jump to: navigation, search

The main class looks as follows:

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]);
        }
        printFirst(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 shall be executed with:

java MyClass 5 blue Hello

And shall output the first parameter so it gives an output like:

The first parameter is: 5

Your work is to implement the printFirst method, you can choose yourself if you want to implement everything with a try/catch in the printFirst method or if you want to call the already existing popFromStack method.

Personal tools