Tuesday, March 20, 2018

arrays - Getting NullPointerException when accessing a variable in a Java class

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.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...