【发布时间】:2011-04-29 17:01:06
【问题描述】:
在 Java 类中设置变量时遇到问题
这是我的代码
这是我创建实例的地方(IdeaInfo 是一个类似于 Struct 的类):
IdeaInfo[] IDEAS = new IdeaInfo[100];
String[] TITLES = new String[100];
这是将使用这些实例的函数:
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++;
}
}
}
这就是我在 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;
}
}
显然,错误发生在 try 内部,正好在 IDEAS[ideas_pos].setTitle(sb.toString());
调试器表明我正在访问 NullPointerException,这对我来说没有任何意义,因为我已经在类中初始化了这些变量。
顺便说一下,我将ideas_pos初始化为0。
【问题讨论】:
-
顺便说一句,您可以将
new String()替换为""。
标签: java arrays class nullpointerexception