【发布时间】:2016-07-30 20:37:44
【问题描述】:
我正在尝试使用 Java 中的数组来实现堆栈。我的 Stack 类由非静态方法 push、pop、peek 和 isempty 组成。我想测试堆栈实现是在主类中的非静态主方法中实例化堆栈。当我尝试这样做时,我收到一个错误“无法从静态上下文引用非静态方法 push(int)” 我做错了什么?
堆栈.java
public class Stack {
private int top;
private int[] storage;
Stack(int capacity){
if (capacity <= 0){
throw new IllegalArgumentException(
"Stack's capacity must be positive");
}
storage = new int[capacity];
top = -1;
}
void push(int value){
if (top == storage.length)
throw new EmptyStackException();
top++;
storage[top] = value;
}
int peek(){
if (top == -1)
throw new EmptyStackException();
return storage[top];
}
int pop(){
if (top == -1)
throw new EmptyStackException();
return storage[top];
}
}
Main.java
public class Main {
public static void main(String[] args) {
new Stack(5);
Stack.push(5);
System.out.println(Stack.pop());
}
}
【问题讨论】:
-
Stack x = new Stack(5);然后x.push();和x.pop(); -
您需要一个变量来保存
Stack对象。Stack s = new Stack(5);那么您的方法将在s上运行。 -
你必须在 Stack 类的对象上调用 push
-
仅供参考:
push()方法中的保护条件是错误的。应该是top == storage.length - 1,异常应该不一样(我的意思是,栈是full,不是empty,对吧?)
标签: java data-structures stack