编译正常却持续抛出java.lang.NumberFormatException问题排查求助
解决NumberFormatException的数组加载问题
看起来你的loadArray方法在尝试把文件每行内容转成整数时栽了跟头——Integer.parseInt(line)抛出了NumberFormatException。这种编译正常但运行报错的情况,通常不是代码逻辑的语法问题,而是文件内容不符合预期,或者代码缺少对异常行的处理。
可能的问题根源
- 你的数据文件里存在空行(比如文件末尾多了一行空白内容),或者某一行包含了非数字字符(比如空格、字母、标点符号)
- 虽然你说之前代码运行正常,但新增方法后可能间接影响了输入输出的上下文,不过核心问题还是出在字符串转整数的步骤上
修复方案
我给你调整了代码,添加了对异常行的处理和日志输出,这样能快速定位到哪一行出了问题:
public static int loadArray(int[] numbers) { System.out.print("Enter the file name: "); String fileName = keyboard.nextLine(); File file = new File(fileName); BufferedReader br; String line; int index = 0; try { br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { // 先去掉前后空格,避免空格导致的转换失败 String trimmedLine = line.trim(); // 跳过空行 if (trimmedLine.isEmpty()) { continue; } try { numbers[index++] = Integer.parseInt(trimmedLine); if(index > 150) { System.out.println("Max read size: 150 elements. Terminating execution with status code 1."); System.exit(0); } } catch (NumberFormatException nfe) { // 输出错误行内容,精准定位问题 System.out.printf("Warning: 无法将行内容 '%s' 转换为整数,跳过该行。%n", line); } } } catch (FileNotFoundException ex) { System.out.println("Unable to open file " + fileName + ". Terminating execution with status code 1."); System.exit(0); }catch(IOException ie){ System.out.println("Unable to read data from file. Terminating execution with status code 1."); System.exit(0); } return index; }
额外排查建议
- 打开你的数据文件,逐行检查是否都是纯数字,有没有多余的空格或空行
- 如果文件是从外部导入的,可能存在隐藏的特殊字符(比如全角空格),可以用文本编辑器的「显示所有字符」功能查看
- 如果你希望遇到无效行时直接终止程序,也可以把内部的catch块改成输出错误后调用
System.exit(1),这样能立刻锁定问题位置
内容的提问来源于stack exchange,提问作者Sam Huegen
相关产品推荐
相关产品推荐

