如何修复Java读取文本文件时出现的NoSuchElementException异常?
问题修复:NoSuchElementException 异常解决及代码优化
问题根源
你的NoSuchElementException确实出在else分支的fileInput.next()调用上,原因是:
- 你用
while (fileInput.hasNextLine())作为循环条件,这个判断的是是否还有下一行,但Scanner的next()/nextInt()是按空白符分割的token单元读取内容。 - 当处理到文件最后一行的最后一个非整数token时,
hasNextLine()返回true(当前行未完全处理),但此时已经没有下一个token了,调用fileInput.next()就会触发无元素可读取的异常。
修复方案
方案1:修改循环判断条件(推荐)
把循环条件从判断是否有下一行,改成判断是否有下一个token,直接用fileInput.hasNext():
while (fileInput.hasNext()) { if(fileInput.hasNextInt()){ data[index] = fileInput.nextInt(); index++; } else { fileInput.next(); // 此时确保有token可读取 } if (index >= data.length){ data = doubleArrayAndCopy(data); } }
方案2:在else分支增加存在性判断
如果坚持按行处理,可以在调用next()前先检查是否还有token:
while (fileInput.hasNextLine()) { if(fileInput.hasNextInt()){ data[index] = fileInput.nextInt(); index++; } else { if (fileInput.hasNext()) { // 先确认还有token再读取 fileInput.next(); } else { break; // 没有元素就退出循环 } } if (index >= data.length){ data = doubleArrayAndCopy(data); } }
额外优化:避免打印未使用的数组元素
原代码排序后会打印数组中未存入数据的默认值0,修改打印逻辑,只输出前index个有效元素:
else { // 仅排序有效元素区间 Arrays.sort(data, 0, index); System.out.println("Elements of array sorted in ascending order: "); // 仅打印有效元素 for (int i = 0; i < index; i++) System.out.println(data[i]); }
完整修改后的代码
package Main; import java.io.*; import java.util.*; public class FilterSort { public static int[] doubleArrayAndCopy(int[] arr) { int SIZE = arr.length; int [] tempArr = new int[2*SIZE]; for (int i = 0; i < SIZE; i++){ tempArr[i] = arr[i]; } return tempArr; } public static void main(String[] args){ int[] data = new int[8]; int index = 0; try { Scanner fileInput = new Scanner(new File("src/main/data.txt")); // 修改循环条件为判断是否有下一个token while (fileInput.hasNext()) { if(fileInput.hasNextInt()){ data[index] = fileInput.nextInt(); index++; } else { fileInput.next(); } if (index >= data.length){ data = doubleArrayAndCopy(data); } } if(index==0){ System.out.println("There is no data in file"); } else { // 仅排序有效元素区间 Arrays.sort(data, 0, index); System.out.println("Elements of array sorted in ascending order: "); // 仅打印有效元素 for (int i = 0; i < index; i++) System.out.println(data[i]); } } catch(FileNotFoundException e){ System.out.println("Error: Data file not found"); } catch(NoSuchElementException e){ // 可选:增加异常捕获,避免程序崩溃 System.out.println("Error: Unexpected end of file"); } } }
内容的提问来源于stack exchange,提问作者Evan
相关产品推荐
相关产品推荐

