0

我创建了一个包含两个字段的数据类型,时间和测量。我创建了这些数据类型的数组。然后,当我尝试将值分配给 array[0] 的一个字段时,我得到一个空指针异常。谁能告诉我出了什么问题?

Public class MeasurementPoint{

private int time;
private double  measurement;

public MeasurementPoint(){
this.time =0;
this.measurement =0;}}

public void setMeausurement(double value){
this.measurement = value;}
public double getMeasurement (){
return this.measurement;}

public void setTime(int value){
this.time = value;}
public int getMeasurement (){
return this.time;}
}

我用来创建数组的代码如下

MeasurementPoint [] controlValues = new MeasurementPoint [points];
System.out.println(controlValues.length(); // this gives me 16 so I know the array is created

controlValues[0].setMeasurement(aCtivity);// this is where I get the exception.
4

1 回答 1

4

您初始化了数组,但从未初始化过Array Elements,因此NullPointerException当您尝试访问数组的第零个索引时会得到结果,因为 yourarray[0] 返回 null 并且您尝试在 null 上调用 setMe...() ..你必须实际初始化你的数组元素。

MeasurementPoint [] controlValues = new MeasurementPoint [points];
controlValues[0] = new Measurementpoint(val1,val2);
于 2013-01-23T09:41:26.157 回答