从Java中的文本文档写入初始化数组时的NullPointerException
正如标题所说,我在从Java中的文本文档写入初始化数组时的NullPointerException,java,arrays,eclipse,nullpointerexception,Java,Arrays,Eclipse,Nullpointerexception,正如标题所说,我在list[I].setName(name)处得到一个NullPointerException
list[I].setName(name)处得到一个NullPointerException我不知道为什么。学生包含姓氏和分数。data.txt的格式为第一行:条目数
第二行:姓名(空格)分数,第三、第四等相同。
Java和堆栈溢出方面的新功能,请告诉我应该提供哪些其他详细信息。有关方法如下:
public static Student [] readListFromFile() {
Scanner s = new Scanner("data.txt");
File fileName;
boolean weGood = false;
while (weGood == false) {
System.out.println("Please enter the file name:");
fileName = new File(getInput()); //user can input their own filename
try {
s = new Scanner(fileName);
weGood = true;
} catch (FileNotFoundException e) {
System.out.println("File not found, please try again");
}
}
int listlength = Integer.parseInt(s.nextLine());
Student [] list = new Student[listlength];
for (int i = 0; i < list.length && s.hasNext() == true; i++) {
String name = s.next();
Double score = Double.parseDouble(s.next());
list[i].setName(name);
list[i].setScore(score);
}
return list;
}
publicstaticstudent[]readListFromFile(){
扫描仪s=新扫描仪(“data.txt”);
文件名;
布尔weGood=false;
while(weGood==false){
System.out.println(“请输入文件名:”);
fileName=新文件(getInput());//用户可以输入自己的文件名
试一试{
s=新扫描仪(文件名);
weGood=true;
}catch(filenotfounde异常){
System.out.println(“未找到文件,请重试”);
}
}
int listlength=Integer.parseInt(s.nextLine());
学生[]列表=新学生[listlength];
对于(int i=0;i
当您创建一个类似
Student[]list=新学生[listlength]代码>
然后所有数组元素最初都是null
。
前list[i].setName(name)代码>引发NullPointerException
您需要在使用数组元素之前初始化它们,例如
Student [] list = new Student[listlength];
for (int i = 0; i < list.length && s.hasNext() == true; i++) {
list[i] = new Student();
...
Student[]list=新学生[listlength];
对于(int i=0;i
是,您需要在使用数组元素之前初始化它们
Student[] list = new Student[listLength];
for(int i=0;i<list.length && s.hasNext() == true;i++){
if(list[i] != null){
list[i] = new Student();
.....
}
}
Student[]list=新学生[listLength];
for(int i=0;list
的i可能重复项是一个listlength
null值的数组。调试会告诉您这一点。