我对此方法有疑问。它返回一个空值,我不确定如何修复它。我看到其他人解释说,直到达到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)
最佳答案
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);
}