我不确定为什么我要为String数组获取java.lang.NullPointerException?我找了好几个小时但找不到任何问题。请帮忙
private String[] stringList;
int j = 0;
StringClass stringRef = new StringClass();
while (//As long as there is string available from what I am reading in)
{
str = //String read in;
stringRef.setString(str);
stringList[j] = stringRef.returnString(); //Shows that this line is the error
j++;
}
这是班级:
public class StringClass {
private String stringNew;
public void setString(String newStr){
stringNew = newStr;
}
public String returnString(){
return stringNew;
}
}
答案 0 :(得分:0)
即使它位于变量List
的名称中,您也没有使用stringList
。列表将动态调整大小,因此您不必在编译时声明初始大小。
以下是我建议更改的代码:
import java.util.ArrayList;
import java.util.List;
...
private List<String> stringList = new ArrayList<String>();
int j = 0;
StringClass stringRef = new StringClass();
while (//As long as there is string available from what I am reading in)
{
str = //String read in;
stringRef.setString(str);
stringList.add(stringRef.returnString()); //Shows that this line is the error
j++;
}