2013-03-24 132 views
1

我想實現一個數組使用2堆棧和緩衝區。 最初堆棧中填充了隨機值,MyArrayI接口包含2個函數:getItemAt(int index)和setItemAt(int index,int item)。並且它們在MyStackArray類中成功實現。 每當我運行程序時,我得到空異常錯誤,我試圖追蹤原因,直到我發現堆棧沒有填充初始數據 - 也許。每當我嘗試訪問堆棧或緩衝區時,都會收到NullPointerException錯誤。當我嘗試打印數組堆棧中的元素時,我仍然得到了愚蠢的NPE錯誤!奇怪的空指針異常

public class MyStackArray implements MyArrayI { 
    private int[] buffer; 
    private int[] stack; 
    private int maxSize; 

    public MyStackArray(int s){ 
     maxSize = s; 
     int[] buffer = new int [maxSize]; 
     int[] stack = new int [maxSize]; 

     for(int i=0; i<maxSize; i++) 
      stack[i]=i; // initiallizing the array with random values. 
    } 

    public void print(){    // tried to check the contents of the stack array. 
     for(int i=0; i<maxSize; i++) 
      System.out.println(stack[i]); // causes Null Pointer Exception. ??! 
     //System.out.println(stack[0]); // still causes the NPE !! 
    } 

    public void setItemAt(int index, int item){ 
     int i; 
     int j; 

      for(i=0, j=maxSize-1 ; i<maxSize && j>=0 ; i++, j--){ 
       if(j == index) 
        break; 
       buffer[i] = stack[j]; //causes a NULL.PointerException 
      } 
      stack[j] = item; 
    } 

    public int getItemAt(int index){ 
     int i; 
     int j; 

      for(i=0, j=maxSize-1 ; i<maxSize && j>=0; i++, j--){ 
       if(j==index) 
        break; 
       buffer[i] = stack[j]; // causes NPE 
      } 
      return stack[j]; 
    } 

    public static void main(String[] args) { 

     MyStackArray X = new MyStackArray(3); 
     //X.setItemAt(0,4); // causes NPE 
     //X.getItemAt(1); // causes NPE 
    X.print();    // causes NPE 
    } 
} 

回答

2
int[] stack = new int [maxSize]; 

在這裏,你正在創建一個名爲stack新的變量 - 這是不一樣的this.stack。你不是想:

stack = new int[maxSize]; // i.e. initialize this.stack, not another variable 

當未初始化,this.stack仍然null,當您嘗試訪問它,你收到NPE。

P.S.你也用buffer做同樣的事情。

1

你沒有正確初始化的變量:

public MyStackArray(int s){ 
    maxSize = s; 
    int[] buffer = new int [maxSize]; // Initializes LOCAL buffer 
    int[] stack = new int [maxSize]; // Initializes LOCAL stack 

    for(int i=0; i<maxSize; i++) 
     stack[i]=i; // initiallizing the array with random values. 
} 

變化是這樣的:

public MyStackArray(int s){ 
    maxSize = s; 
    buffer = new int [maxSize]; 
    stack = new int [maxSize]; 

    for(int i=0; i<maxSize; i++) 
     stack[i]=i; // initiallizing the array with random values. 
} 
1

你實際上是在你的構造函數初始化新的(本地)陣列。你有

public MyStackArray(int s){ 
    maxSize = s; 
    int[] buffer = new int [maxSize]; //You are declaring new array 
    int[] stack = new int [maxSize]; //You are declaring new array 

    for(int i=0; i<maxSize; i++) 
     stack[i]=i; // initiallizing the array with random values. 
} 

但你應該不是這個在構造函數:

public MyStackArray(int s){ 
    maxSize = s; 
    buffer = new int [maxSize]; 
    stack = new int [maxSize]; 

    for(int i=0; i<maxSize; i++) 
     stack[i]=i; // initiallizing the array with random values. 
}