创建用户定义的数据类型,给出问题

时间:2013-01-23 09:37:02

标签: java nullpointerexception initialization custom-data-type

我创建了一个包含两个字段,时间和度量的数据类型。我创建了这些数据类型的数组。当我然后尝试将值赋给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.

1 个答案:

答案 0 :(得分:4)

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

MeasurementPoint [] controlValues = new MeasurementPoint [points];
controlValues[0] = new Measurementpoint(val1,val2);