在类实例化时出错

时间:2013-11-21 15:50:41

标签: java

这里有新的Java用户。需要有关课堂作业的帮助。 这段代码有什么作用?为什么我在Stack s = new Stack(10)上收到错误;和s.top()方法。

public class StackExample 
{
     public static void main(String[] args)
     {
        Stack s = new Stack(10);

        System.out.println("Adding 33 and 47 to stack.");
        // push adds the item to the top of the stack
        s.push(33);
        s.push(47);  

        System.out.println("Top of stack: " + s.top());
        System.out.println("Items in stack: " + s.size());

        // pop removes the top item
        System.out.println("Removing top item.");
        s.pop();     

        System.out.println("Top of stack: " + s.top());
        System.out.println("Items in stack: " + s.size());
        System.out.println("Adding a new item.");
        s.push(3);
        System.out.println("Top of stack: " + s.top());
        System.out.println("Items in stack: " + s.size());
     }
}

1 个答案:

答案 0 :(得分:1)

你必须阅读javadoc: http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

没有接受大小的构造函数。

没有top方法。要查看该项而不检索该项,请使用peek。否则pop

这应该有用。

public class StackExample 
{
     public static void main(String[] args)
     {
        Stack s = new Stack();

        System.out.println("Adding 33 and 47 to stack.");
        // push adds the item to the top of the stack
        s.push(33);
        s.push(47);  

        System.out.println("Top of stack: " + s.peek());
        System.out.println("Items in stack: " + s.size());

        // pop removes the top item
        System.out.println("Removing top item.");
        s.pop();     

        System.out.println("Top of stack: " + s.peek());
        System.out.println("Items in stack: " + s.size());
        System.out.println("Adding a new item.");
        s.push(3);
        System.out.println("Top of stack: " + s.peek());
        System.out.println("Items in stack: " + s.size());
     }
}