My code doesn't seem to work when the string token is an int. Here it is:
public class CO2Data {
CO2Data dataSet[] = new CO2Data[10];
String strLine = "Italy 476.08 116.86 2 592";
int lines = 10;
double roadCO2;
public void saveLineInfo(String strLine, int lines) {
StringTokenizer token = new StringTokenizer(strLine);
String str = "hello";
int count = 0;
for (int i = 0; i < lines; i++) {
while (token.hasMoreTokens()) {
str = token.nextToken();
if (count == 3) {
getRoadCO2(str, roadCO2);
dataSet[i].setRoadCO2(roadCO2);
}
count++;
}
}
}
public double getRoadCO2(String str, double roadCO2) {
roadCO2 = Double.parseDouble(str);
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
}
In the rest of the lines, roadCO2 is a double, so I'm guessing my program is getting confused? How do I fix it? Thanks so much!
NullPointerException
at line 56 of your original program (possibly the system out println) looking at the code you have given us. Only reasonable explanation is that dataSet[1]
is null
- ring bearer 2012-04-04 04:09
You are getting NullPointerException because,
You've declared an Array of CO2Data dataSet[] = new CO2Data[10];
,
but every element inside this CO2Data[] array
is pointing to Null.
Hence, this call: dataSet[i].setRoadCO2(roadCO2);
will generate a NullPointerException
because dataSet[i]
is pointing to null
.
Solution :
Instantiate dataSet[i] = new CO2Data();
then call dataSet[i].setRoadCO2(roadCO2);
I'd recommend changing the names of the parameters to your methods to something slightly different than the class datamember "roadCO2". That might help you sort out the error :)
When I ran your code, I got a NullPointerException at line 22. This is beacuse the array 'data' has not been initialized.
You can initialize your array as follows
for(int i = 0; i < dataSet.length; i++) {
dataSet[i] = new CO2Data();
}