I have a problem when setting a variable inside a Java class
Here is my code
This is where I create the instances (IdeaInfo is a class that acts similar to a Struct):
IdeaInfo[] IDEAS = new IdeaInfo[100];
String[] TITLES = new String[100];
This is the function that will use those instances:
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
// This is adding title to array Ideas and Titles
if(mode % 3 == 0) {
IDEAS[ideas_pos].setTitle(sb.toString());
TITLES[titles_pos] = sb.toString();
titles_pos++;
mode++;
}
// This is adding the content to array Ideas
else if(mode % 3 == 1) {
IDEAS[ideas_pos].mContent = sb.toString();
mode++;
}
// This is adding the rating to array Ideas
else if(mode % 3 == 2) {
IDEAS[ideas_pos].mRating = Float.valueOf(sb.toString().trim()).floatValue();
ideas_pos++;
mode++;
}
}
}
This is what I have inside IdeaInfo class:
public class IdeaInfo {
public String mTitle = new String(); // Store the Idea's title
public String mContent = new String(); // Store the Idea's title
public float mRating; // Store the Idea's Rating
/*
* Function that set the Idea's title
*/
public void setTitle(String temp){
mTitle = temp;
}
}
Apparently, the error occurred inside the try, exactly at IDEAS[ideas_pos].setTitle(sb.toString());
The debugger indicated that I am accessing a NullPointerException, this does not really make any sense to me since I already initialize those variables in the class.
By the way, I initialized ideas_pos to 0.
Arrays in java are initialized “clean”, that is, with all elements set to
nullor “zero” (whatever is appropriate for the type of array). When you writethe JVM will treat it as if you wrote
This takes some getting used to if you are coming to Java from a language like C or C++ which has different conventions for initializing arrays.