我正在嘗試創建一個程序,它將生成T個案例中兩個給定整數(A & B)之間的所有素數。我正在實施Eratosthenes的主篩。我的代碼如下。我已經讀過代碼中提到的那一行的NullPointerException,這是我沒有初始化布爾數組的結果。不過,我想我已經在這裏做這樣的:布爾數組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')。無論如何,問題是'(布爾)((布爾)空)'導致NPE。 – user2864740