如何解决Java读取输入时Integer.parseInt抛出NumberFormatException: null问题
异常根因分析
- 触发
java.lang.NumberFormatException: null的核心原因是BufferedReader.readLine()返回了空值,被直接传入Integer.parseInt()做类型转换,说明输入流已经没有可读取的内容。最常见的触发场景是代码读取逻辑和输入格式完全不匹配:你提供的输入示例中,除了第一行的轮次N外,后续每一行是两个空格分隔的得分值,但原代码在循环中每次调用两次readLine()分别读取两个得分,相当于期望每个得分单独占一行,逻辑不匹配会提前耗尽输入流,最终读到空值触发异常。 - 次要触发原因:运行程序时未提供任何标准输入内容,第一行读取就直接返回空值触发报错。
解决步骤
- 修正循环内的读取逻辑,每次读取一行后按空格拆分出两个得分值,不要分两次读取行
- 增加非空判断,避免
readLine()返回空值时直接做类型转换 - 本地测试时输入完所有内容后,按
Ctrl+D(Windows系统按Ctrl+Z)标记输入结束,避免程序读到空值
修正后代码
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class Alex { public static void main (String[] args) throws IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); int cumScore1 = 0; int cumScore2 = 0; int maxLead = -1; int winner = -1; // 增加非空判断 String nLine = br.readLine(); if (nLine == null || nLine.isBlank()) { return; } int N = Integer.parseInt(nLine.trim()); for (int i = 0; i < N; i++) { String scoreLine = br.readLine(); if (scoreLine == null || scoreLine.isBlank()) { break; } // 拆分单行的两个得分 String[] scores = scoreLine.trim().split("\\s+"); int S = Integer.parseInt(scores[0]); int T = Integer.parseInt(scores[1]); cumScore1 += S; cumScore2 += T; int lead = cumScore1 - cumScore2; int absLead = Math.abs(lead); if (absLead > maxLead) { maxLead = absLead; winner = lead > 0 ? 1 : 2; } } System.out.println(winner + " " + maxLead); } }
内容的提问来源于stack exchange,提问作者Mama
相关产品推荐
相关产品推荐

