为何读取文本文件生成二维数组的Java代码无限运行?
问题分析与解决
你的代码出现无限循环的核心原因是内部统计列数的while循环中,只判断了colReader.hasNextInt(),但没有调用nextInt()来移动Scanner的指针。只要当前行存在整数,这个判断会一直返回true,循环永远不会终止——因为Scanner的指针始终停留在同一个整数前,重复触发hasNextInt()为true的判断。
修正后的代码(适配每行列数一致的场景,用于创建二维数组)
public static void loadState() throws FileNotFoundException { Scanner input = new Scanner(new File("large.txt")); int rows = 0; int cols = 0; // 先读取第一行确定列数 if (input.hasNextLine()) { Scanner colReader = new Scanner(input.nextLine()); while (colReader.hasNextInt()) { cols++; colReader.nextInt(); // 关键:消耗输入,移动指针 } rows++; // 第一行已统计 } // 统计剩余行数,可额外验证每行列数是否一致 while (input.hasNextLine()) { rows++; Scanner colReader = new Scanner(input.nextLine()); int currentCols = 0; while (colReader.hasNextInt()) { currentCols++; colReader.nextInt(); } if (currentCols != cols) { System.err.println("行" + rows + "的列数与第一行不一致"); } } input.close(); System.out.println(cols + "==" + rows); }
若需统计所有整数总数(适配每行列数不同的场景)
public static void loadState() throws FileNotFoundException { Scanner input = new Scanner(new File("large.txt")); int rows = 0; int cols = 0; while (input.hasNextLine()) { rows++; Scanner colReader = new Scanner(input.nextLine()); while (colReader.hasNextInt()) { cols++; colReader.nextInt(); // 必须添加此行移动指针 } } input.close(); System.out.println(cols + "==" + rows); }
内容的提问来源于stack exchange,提问作者Anwar Hashmi
相关产品推荐
相关产品推荐

