在我的類的構造函數中,我初始化了一個帶有boolean[] list = new boolean[n]
的布爾數組,其中n
是構造函數的唯一參數,我將list
的每個索引分配給true
和Arrays.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異常,即使我初始化所有的list
與Arrays.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建議的修改。
顯示的構造函數(我懷疑你是陰影'list')。 – August 2015-02-07 05:25:30
顯示你所有的構造函數,以及這個n如何仍然指向構造函數中的參數 – Tarik 2015-02-07 05:32:59