【问题标题】:Boolean Array NullPointerException [duplicate]布尔数组 NullPointerException [重复]
【发布时间】: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


【解决方案1】:

您创建了一个Boolean 对象数组,但它们都被初始化为null。您确实将大部分元素显式初始化为true,但仅从索引2 开始。

假设这是符合 NPE 的路线:

if(N[m]){

mA 开头,根据您提供的输入,这似乎是1。但这从未被初始化。 1 既不是质数也不是合数,所以你应该单独处理这种情况。

【讨论】:

  • 当我为索引 0 和 1 添加特殊情况时它可以工作。谢谢。
【解决方案2】:

关于对象数组,尝试如下初始化:

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

【讨论】:

    猜你喜欢
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多