我已经搜索了这个问题并找到了很多关于它的答案,但是我不理解它们,我想对我自己的代码进行澄清,所以希望它有意义
我正在尝试在 main 方法中调用 PrintList 方法
但我收到这个错误
无法从 Stack 类型对非静态方法 PrintList() 进行静态引用
如果我将 PrintList 的修饰符更改为 static ,则会破坏整个代码。
谁能帮我解决这个问题吗?
Thanks
public class Stack<Item> {
public int N; // size of the stack
public Node<Item> first; // top of stack
public Node<Item> last; // top of stack
// helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
public Stack() {
first = null;
last = null;
N = 0;
}
public void PrintList() {
Node<Item> current;
current = first;
while (current.next != null) {
System.out.println(current.item);
current = current.next;
}
}
public static void main(String[] args) {
// Declare the stack
Stack<String> s = new Stack<String>();
s.push("Bob");
s.push("Mary");
s.push("David");
s.InsertBegin("George");
System.out.println("First item: " + s.peek());
Object current;
PrintList(); // what is wrong here?
}
}
问题是您没有指定实例PrintList
是要被召唤的。要解决这个问题,请更改以下内容:
PrintList(); // what is wrong here?
to this:
s.PrintList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)