
首先需要明确的是,java.util.NoSuchElementException是一个运行时异常 (Runtime Exception),而不是编译错误。这意味着Java编译器在编译代码时无法检测到此问题,它只会在程序实际运行时,当尝试从输入源(如文件或控制台)读取下一个元素但该源已没有可用的元素时才会被抛出。
在文件读取的上下文中,NoSuchElementException通常发生在以下情况:
在处理类似“生命游戏”等需要从文本文件读取网格数据的应用中,常见的输入文件格式可能是这样的:
示例文件:Blinker.txt
立即学习“Java免费学习笔记(深入)”;
5 5 00000 00000 01110 00000 00000
这里,第一行5 5表示网格的行数和列数,接下来的行则表示网格的具体数据。问题在于,数据行如00000被视为一个连续的字符串,而不是五个独立的整数。
如果使用如下代码尝试读取:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class GameOfLifeProblem {
public static int fileRow, fileColumn;
public static int[][] array;
public static int[][] readGrid(String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file); // 局部Scanner,避免与全局混淆
fileRow = fileScanner.nextInt(); // 读取行数:5
fileColumn = fileScanner.nextInt(); // 读取列数:5
array = new int[fileRow][fileColumn];
for (int i = 0; i < fileRow; i++) {
for (int j = 0; j < fileColumn; j++) {
// 尝试读取25个整数
array[i][j] = fileScanner.nextInt(); // 这里会出问题
}
}
fileScanner.close(); // 关闭资源
return array;
}
public static void main(String[] args) throws IOException {
// 假设用户输入 "Blinker.txt"
// array = readGrid("Blinker.txt");
}
}当程序执行到array[i][j] = fileScanner.nextInt();时,Scanner在读取完初始的5和5之后,会尝试寻找下一个整数标记。然而,文件中的下一行是00000。对于nextInt()而言,00000是一个单一的字符串标记,而不是五个独立的整数标记。当nextInt()尝试将其解析为整数时,它可能成功解析出0(如果分隔符允许),但很快就会发现后续没有足够的独立整数标记来填充整个5x5的网格(它只找到了00000、00000、01110等总共5个字符串标记),当它尝试读取第6个整数时,文件已没有更多的有效整数标记,因此抛出NoSuchElementException。
正确的处理方法是,将每一行数据作为一个完整的字符串读取,然后逐个字符地解析该字符串,将其中的'0'或'1'转换为对应的整数。
修正后的readGrid方法示例:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.InputMismatchException; // 导入InputMismatchException
public class GameOfLifeTutorial {
public static final char ON = 'X';
public static final char OFF = '*';
public static int fileRow, fileColumn;
public static int[][] array;
public static Scanner consoleScanner = new Scanner(System.in); // 用于控制台输入的Scanner
/**
* 从指定文件中读取网格数据。
* 文件格式预期:
* 第一行:行数 列数 (例如: 5 5)
* 接下来N行:每行一个由0和1组成的字符串 (例如: 00000)
*
* @param fileName 要读取的文件名。
* @return 解析后的二维整数数组。
* @throws IOException 如果文件不存在或读取过程中发生IO错误。
* @throws InputMismatchException 如果文件内容格式不符合预期(如数据不足或行长度不匹配)。
* @throws NumberFormatException 如果字符串中的字符无法解析为0或1。
*/
public static int[][] readGrid(String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = null; // 声明为null,以便在finally块中安全关闭
try {
fileScanner = new Scanner(file);
// 1. 读取网格尺寸
if (!fileScanner.hasNextInt()) {
throw new InputMismatchException("文件缺少网格行数定义。");
}
fileRow = fileScanner.nextInt(); // 读取行数
if (!fileScanner.hasNextInt()) {
throw new InputMismatchException("文件缺少网格列数定义。");
}
fileColumn = fileScanner.nextInt(); // 读取列数
array = new int[fileRow][fileColumn];
// 2. 逐行读取网格数据
for (int i = 0; i < fileRow; i++) {
// 检查文件是否还有下一行数据,防止在文件末尾抛出 NoSuchElementException
if (!fileScanner.hasNext()) {
throw new InputMismatchException("文件数据不足,期望 " + fileRow + " 行,但实际只读取到 " + i + " 行数据。");
}
String rowString = fileScanner.next(); // 读取整行字符串,例如 "00000"
// 验证行长度
if (rowString.length() != fileColumn) {
throw new InputMismatchException("文件第 " + (i + 1) + " 行的列数不匹配,期望 " + fileColumn + " 列,实际 " + rowString.length() + " 列。");
}
// 3. 逐字符解析字符串并转换为整数
for (int j = 0; j < fileColumn; j++) {
char cellChar = rowString.charAt(j);
if (cellChar == '0' || cellChar == '1') {
// Character.getNumericValue() 是一个更通用的方法,用于将字符 '0'-'9' 转换为对应的整数
array[i][j] = Character.getNumericValue(cellChar);
} else {
throw new NumberFormatException("文件包含非法的字符:'" + cellChar + "' 在第 " + (i + 1) + " 行,第 " + (j + 1) + " 列。期望 '0' 或 '1'。");
}
}
}
} finally {
// 确保 Scanner 资源被关闭,防止资源泄露
if (fileScanner != null) {
fileScanner.close();
}
}
return array;
}
public static void main(String[] args) {
String fileName;
System.out.print("请输入您要使用的文件名 (例如: Blinker.txt): ");
fileName = consoleScanner.nextLine(); // 从控制台读取文件名
try {
array = readGrid(fileName);
// 打印读取到的数组内容进行验证
System.out.println("\n成功读取文件内容:");
for (int i = 0; i < fileRow; i++) {
for (int j = 0; j < fileColumn; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
} catch (IOException e) {
System.err.println("文件读取错误: " + e.getMessage());
} catch (InputMismatchException | NumberFormatException e) {
System.err.println("文件内容格式错误: " + e.getMessage());
} finally {
// 关闭用于控制台输入的Scanner
if (consoleScanner != null) {
consoleScanner.close();
}
}
}
}代码解析:
以上就是Java文件输入中NoSuchElementException的解析与健壮处理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号