2015-02-07 78 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