1

我有一个包含双精度数组的对象。

public class NumberRow {

static final int MAX_AMOUNT_OF_NUMBERS = 2500;
double[] NumberArray = new double[MAX_AMOUNT_OF_NUMBERS];

NumberRow(double[] NumberArray){
    this.NumberArray = NumberArray;
}

}

在我的主程序中,我首先在构造函数中创建对象 NumberRow 的数组,如下所示

NumberRow[] numberRow;

稍后在程序中我放了这段代码:

numberRow = new NumberRow[dataset.numberOfVariables];

之后,我调用一个为 numberRow 赋值的函数:

double misc = in.nextDouble();
numberRow[k].NumberArray[i] = misc;

我确实说过 NumberRow 指向的地方。但是,eclipse 在这一行给了我一个空指针指针异常:

numberRow[k].NumberArray[i] = misc;

我希望任何人都可以看到我做错了什么?谢谢 :)!

4

2 回答 2

1

When you do this:

numberRow = new NumberRow[dataset.numberOfVariables];

All of the members of the array numberRow are initialized to the default value of NumberRow. NumberRow is a class, therefore its default value is null. To set values on something that is null, you must first initialize it to a new, real object or you will get a NullPointerException.

于 2013-06-05T00:16:04.927 回答
1

This is a common mistake I see when beginners start to use arrays of objects. When an array of object references is created, the array is initialized, but the individual elements in the array are null. So, on the statement numberRow[k].NumberArray[i] = misc;, numberRow[k] is null, which is causing the exception. Therefore, before the line, you need to put the statement

numberRow[k] = new NumberRow();

before the above statement.

于 2013-06-05T00:18:26.097 回答