在我的类的构造函数中,我初始化了一个带有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