访问Java类中的变量时获取NullPointerException

Sam*_*mmm 2 java arrays class nullpointerexception

在Java类中设置变量时遇到问题

这是我的代码

这是我创建实例的地方(IdeaInfo是一个类似于Struct的类):

IdeaInfo[] IDEAS = new IdeaInfo[100];
String[] TITLES = new String[100];
Run Code Online (Sandbox Code Playgroud)

这是将使用这些实例的函数:

    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++;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我在IdeaInfo类中的内容:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,错误发生在try中,正是在IDEAS[ideas_pos].setTitle(sb.toString()); 调试器上表明我正在访问NullPointerException,这对我来说没有任何意义,因为我已经在类中初始化了这些变量.

顺便说一句,我初始化ideas_pos为0.

Boz*_*zho 7

初始化数组时,并不意味着您已初始化其成员.

IDEAS[x]null.您需要通过以下方式初始化它:

IDEAS[ideas_pos] = new IdeaInfo();
Run Code Online (Sandbox Code Playgroud)