我对这种方法有疑问。它返回一个空值,我不知道如何解决它。我看到其他人解释说循环没有停止,直到达到null并因此返回null,但我不明白如何解决这个问题。提前致谢
public static int[] readFile(File file) throws IOException {
Scanner fileRead = new Scanner(file);
int a = 0;
while(fileRead.hasNext()) {
a++;
fileRead.nextLine();
}
String[]pieces = new String[a];
while (fileRead.hasNext()) { // i think the error is happening right here
String line = fileRead.nextLine();
pieces = line.split(",");
}
fileRead.close();
int[] piecesNum = new int [pieces.length];
for (int b = 0; b < pieces.length; b++) {
piecesNum[b] = Integer.parseInt(pieces[b]); // line 86
}
return piecesNum;
错误
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Proj5.readFile(Proj5.java:86)
at Proj5.main(Proj5.java:23)
答案 0 :(得分:1)
pieces[b]
的结果为null
且无法解析为Integer
。
请尝试以下方法之一:
处理异常
try{
piecesNum[b] = Integer.parseInt(pieces[b]);
} catch (NumberFormatException e) {
// do something
}
确认内容不为空且为数字
String piece = pieces[b];
if(piece != null && piece.matches("\\d*")){
piecesNum[b] = Integer.parseInt(piece);
}