我設置一個Java類獲得的NullPointerException Java類
這裏面變量時有一個問題訪問變量的時候是我的代碼
這是我創建的實例(IdeaInfo是一個類,作用類似於一個結構):
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()'。 – 2010-10-24 00:16:55