如何解决尝试返回数组列表时出现空指针异常
private ArrayList<Record> readFromFile(String fileName) {
int lineNumber = 0;
Scanner fileReader;
ArrayList<Record> recs = new ArrayList<>();
try {
fileReader = new Scanner(new File(fileName));
while(fileReader.hasNextLine()) {
lineNumber++;
String line = fileReader.nextLine();
String stateCode = line.substring(0,2).trim();
String distCode = line.substring(3,8).trim();
String distName = line.substring(9,81).trim();
int population = Integer.parseInt(line.substring(82,90).trim());
int childPopulation = Integer.parseInt(line.substring(91,99).trim());
int childPovertyPopulation = Integer.parseInt(line.substring(100,108).trim());
String miscStats = line.substring(109).trim();
String[] data = new String[6];
data[0] = stateCode;
data[1] = distCode;
data[2] = distName;
data[3] = String.valueOf(population);
data[4] = String.valueOf(childPopulation);
data[5] = String.valueOf(childPovertyPopulation);
data[6] = miscStats;
recs.add(new Record(stateCode,distCode,distName,population,childPopulation,childPovertyPopulation,miscStats));
}
fileReader.close();
} catch(FileNotFoundException fnfe) {
System.out.println("Cannot locate file: " + fileName);
System.exit(0);
}
return recs;
}
当我尝试返回“ recs”并抛出NullPointerException时,该方法的末尾会发生错误。为什么会这样?
解决方法
从代码中很难看出来,但是我认为fileReader.hasNextLine()
返回的是false,并且没有运行while循环。
将一个println放入while循环中。如果您输入类似System.out.println("Found next lines");
如果您在输出中看不到它,则说明它没有运行循环。
您的代码正在查找文件,因为它没有返回FileNotFoundException,但是在检查下一行时它没有返回false。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。