문제

I have created a datatype with two fields, time and measurement. I create an array of these datatypes. When i then attempt to assign a value to one of the fields of array[0] I get a null pointer exception. can anyone tell me what is wrong?

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;}
}

The code that I use to create the Array is below

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.
도움이 되었습니까?

해결책

You initialized your array but you never initialized your Array Elements, thus you get NullPointerException when you try to acess the zero'th index of your array as yourarray[0] returns null and you try to call setMe...() on null.. you have to actually initialize your array elements.

MeasurementPoint [] controlValues = new MeasurementPoint [points];
controlValues[0] = new Measurementpoint(val1,val2);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top