gpt4 book ai didi

java - 类实例化时出错

转载 作者:行者123 更新时间:2023-12-01 13:48:56 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

这应该有效。

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());
}
}

关于java - 类实例化时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20125564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com