2016-07-30 86 views
-2

我想在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()); 

} 
} 
+0

这是关于使用static关键字https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html –

+1

'Stack x = new Stack(5);'then'x.push();'和'x.pop();' – khelwood

+0

您需要一个变量来保存'Stack'对象。 'Stack s = new Stack(5);'然后你的方法将在's'上运行。 – ajb

回答

1

您已经创建了一个新的实例,但没有保存任何地方引用,因此在创建后立即失去了它。相反,你应该把它分配给一个变量,然后应用在它的方法:

​​
+0

我根据您的评论进行了更改。我得到一个错误**异常在线程“主”java.lang.NoSuchMethodException:Stack.main([Ljava.lang.String;)** – Batman

+0

其实我认为这是因为我引用一个私有变量。谢谢 ! – Batman