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("");
}
}
}
배열을 사용한다면'boolean []'(기본값은'false')입니다. 어쨌든, 문제는'(boolean) ((Boolean) null)'이 NPE가된다는 것입니다. – user2864740