2014-04-28 2 views
-2

T 경우에 주어진 두 정수 (A & B) 사이의 모든 소수를 생성하는 프로그램을 만들려고합니다. 에라 토 스테 네스의 프라임 체 (Prime Sieve of Eratosthenes)를 구현하고 있습니다. 내 코드는 아래와 같습니다. 나는 코드에서 언급 한 라인이 부울 배열을 초기화하지 않은 결과 일 것이라고 NullPointerException을 읽었다. 그러나 여기에서이 작업을 수행했다고 생각했습니다.부울 배열 NullPointerException

Boolean[] N = new Boolean[B+1]; 

따라서이 예외가 throw되는 이유에 대해서는 혼란 스럽습니다. 다른 가능한 원인이 없음을 알고 있습니다. 내 코드에 어떤 문제가 있습니까?

내 오류 및 입력 :

내 코드
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')입니다. 어쨌든, 문제는'(boolean) ((Boolean) null)'이 NPE가된다는 것입니다. – user2864740

답변

0

당신은 배열을 만들었습니다 Boolean 개체가 있지만 모두는로 초기화됩니다.. 대부분의 요소를 명시 적으로 true으로 초기화하지만 인덱스는 2부터 시작합니다.

이가 NPE와 함께 라인 가정 : 당신이 준 입력에 따라 1 것으로 보인다 A에서

if(N[m]){ 

m 시작한다. 그러나 그것은 결코 초기화되지 않았습니다. 숫자 1은 소수도 복합도 아니므로이 사례를 별도로 처리해야합니다.

+0

인덱스 0과 1에 특별한 경우를 추가하면 작동합니다. 고맙습니다. –

0

객체의 배열에 관해서는 다음과 같이 초기화 시도 :

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