2015-02-07 45 views
0

在我的類的構造函數中,我初始化了一個帶有boolean[] list = new boolean[n]的布爾數組,其中n是構造函數的唯一參數,我將list的每個索引分配給trueArrays.fill(list, true)。編輯:list首先然後,在我這樣做的方法構造之外創建與private boolean[] list爲什麼我在這個布爾數組上得到一個NullPointerException?

//n still refers to the parameter in the constructor 
for(int i = 2; i < n; i++){ 
    if(list[i]){ 
     for(int j = i; j < n; j*=i){ 
      list[j] = false; 
     } 
    } 
} 

而且if(list[i])拋出NullPointerException異常,即使我初始化所有的listArrays.fill(list, true)。我原本有一個循環,將list中的所有內容都設置爲true,並給出了相同的錯誤,所以現在我很難過。

編輯:這裏是完整的構造函數。

public Seive(int n){ 

     //create an array of booleans of length n 
     list = new boolean[n]; 
     this.n = n; 

     //set all booleans in the array to true 
     Arrays.fill(list, true); 

     //set 0 and 1 to false so that the algorithm can ignore them 
     //and they won't be put into the list of primes 
     list[0] = false; 
     list[1] = false; 

} 

我離開一件事的是,我才意識到是重要的:我創建list外面與private boolean[] list的構造,使異常拋出的方法應該能夠訪問陣列。在發佈這個代碼塊之前,我也做了Eran建議的修改。

+1

顯示的構造函數(我懷疑你是陰影'list')。 – August 2015-02-07 05:25:30

+0

顯示你所有的構造函數,以及這個n如何仍然指向構造函數中的參數 – Tarik 2015-02-07 05:32:59

回答

1

既然你有這個 - boolean[] list = new boolean[n]; - 在你的構造函數中,這個數組是在構造函數的本地聲明和初始化的。該方法訪問具有相同名稱(可能是您在類中聲明的成員)的未初始化的不同數組。

更改初始化在構造函數:

list = new boolean[n]; 
+0

我試過這個,我仍然得到相同的東西。 – bagochips44 2015-02-07 15:10:27

相關問題