[英]Reading from file returns null
I'm having an issue with this method. 我对此方法有疑问。 It's returning a null value, and I'm not sure how to fix it. 它返回一个空值,我不确定如何修复它。 I saw someone else explaining that the loop doesn't stop until null is reached and therefore returns null, but I don't understand how to get around this. 我看到其他人解释说,直到达到null并因此返回null,循环才会停止,但是我不知道该如何解决。 Thanks in advance 提前致谢
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;
The error 错误
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)
The outcome of pieces[b]
is null
and that cannot be parsed to Integer
. pieces[b]
的结果为null
,无法将其解析为Integer
。
Try one of the following: 请尝试以下方法之一:
Handle the exception 处理异常
try{ piecesNum[b] = Integer.parseInt(pieces[b]); } catch (NumberFormatException e) { // do something }
Verify that content is not null and is a digit 验证内容不为空且为数字
String piece = pieces[b]; if(piece != null && piece.matches("\\\\d*")){ piecesNum[b] = Integer.parseInt(piece); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.