【发布时间】:2014-04-28 18:25:26
【问题描述】:
我正在尝试创建一个程序,该程序将为 T 情况生成两个给定整数(A 和 B)之间的所有素数。我正在实施 Eratosthenes 的 Prime Sieve。我的代码如下。我已经读过代码中提到的行的 NullPointerException 将是我没有初始化布尔数组的结果。但是,我以为我在这里做到了:
Boolean[] N = new Boolean[B+1];
因此,我对抛出此异常的原因感到困惑。我知道没有其他可能的原因。我的代码有什么问题?
我的错误和输入:
1 1 5
Exception in thread "main" java.lang.NullPointerException
at PrimeNumberFinder.main(PrimeNumberFinder.java:27)
我的代码:
class PrimeNumberFinder {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//read the number of cases of the problem to expect from input
int T = sc.nextInt();
//complete for every case
for(int i = 1; i<=T; i++){
//read the boundaries to find primes between
int A = sc.nextInt();
int B = sc.nextInt();
//create boolean array to store primes, according with the Sieve
Boolean[] N = new Boolean[B+1];
//set all values to true
for(int j = 2; j<=B; j++){
N[j]=true;
}
//test for primes for all elements of 'N'
for(int k=2; k*k<=B; k++){
if(N[k]){
for(int l = k; l*k<=B; l++){
N[l*k]=false;
}
}
}
//for all prime elements of N between the desired boundaries(A,B) print
for(int m = A; m<=B; m++){
//this is the line(below) for which the error appears: NullPointerException
if(N[m]){
System.out.println(m);
}else{
continue;
}
}
System.out.println("");
}
}
}
【问题讨论】:
-
如果你要使用数组,
boolean[](默认值为false)。无论如何,问题在于(boolean)((Boolean)null)会导致 NPE。
标签: java nullpointerexception boolean primes