2014-04-28 65 views
-2

我正在嘗試創建一個程序,它將生成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(""); 
     } 
    } 
} 
+1

如果您要使用數組,則使用'boolean []'(默認值爲'false')。無論如何,問題是'(布爾)((布爾)空)'導致NPE。 – user2864740

回答

0

您已經創建了一個數組Boolean對象,但它們全部初始化爲null。您明確地將大多數元素初始化爲true,但僅從索引2開始。

假設這是與NPE行:在A

if(N[m]){ 

m開始出現根據您所提供的輸入視爲1。但是這從未初始化。 1既不是素數也不是複合數,所以你應該分開處理這種情況。

+0

它適用於我爲索引0和1添加特殊情況。謝謝。 –

0

關於Array對象,儘量初始化像這樣:

Boolean[] N = new Boolean[B+1]; 
for(int i=0;i<B+1;i++) 
    N[i]=new Boolean();