我想在Java中使用数组实现堆栈。我的Stack类包含非静态方法push,pop,peek和isempty。我想测试堆栈实现,在主类中的非静态main方法中实例化堆栈。当我尝试这样做时,出现错误“无法从静态上下文中引用非静态方法push(int)” 我在做什么错了?在Java中的堆栈实现
Stack.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());
}
}
这是关于使用static关键字https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html –
'Stack x = new Stack(5);'then'x.push();'和'x.pop();' – khelwood
您需要一个变量来保存'Stack'对象。 'Stack s = new Stack(5);'然后你的方法将在's'上运行。 – ajb