这里有新的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());
}
}
答案 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());
}
}