2016-07-30 80 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