0

我創建了一個包含兩個字段(時間和度量)的數據類型。我創建了這些數據類型的數組。當我然後試圖分配一個值的數組[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. 
+0

setMeaureure(),你正在調用setMeasurement()...這是一個錯字嗎? – Renjith

回答

4

您初始化您的數組,但你永遠不初始化您數組元素,這樣你可以獲得NullPointerException當您嘗試接取零'你的數組的索引作爲yourarray [0]返回null,你嘗試在null上調用setMe ...()..你必須實際初始化你的數組元素。

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

非常感謝那:) – DavyGravy

相關問題