无法将TXT文件内容存入二维数组,求问题排查与解决
代码问题分析与修正
核心问题总结
你的代码存在文件读取失败、二维数组存储逻辑错误、最小值统计逻辑错误三个关键问题,导致数组全为默认0值,最终统计结果异常。
具体问题与修复方案
1. Scanner无法解析带逗号的数值
文件中的数值格式是29432, 113244, 96324,默认Scanner仅按空白符分割内容,遇到逗号会把29432,当作无法解析的token,导致nextInt()读取失败,数组始终保持初始的0值。
修复:修改Scanner的分隔符,匹配逗号加任意空白字符:
Scanner fileInput = new Scanner(file); fileInput.useDelimiter(",\\s*"); // 匹配逗号+任意数量空格
2. 二维数组存储逻辑混乱
- 你创建了
SIZE x SIZE的二维数组,但仅给每一行的第0列赋值,其余列全为默认0; - 循环条件用
hasNextLine()搭配nextInt()逻辑矛盾:nextInt()会跨行读取整数,hasNextLine()判断的是是否有下一行,而非是否有下一个整数,导致读取不完整或提前终止。
修复:如果要将所有数值按顺序填充到二维数组(每行放SIZE个),修改读取逻辑:
int row = 0; int col = 0; while (fileInput.hasNextInt() && row < SIZE) { elevations[row][col] = fileInput.nextInt(); col++; if (col == SIZE) { row++; col = 0; } }
3. 最小值统计逻辑错误
- 初始化
count=0,但第一次遇到初始min值(numbers[0][0])时不会计数; - 当数组全为0时,
minValue初始为0,后续所有0都会触发else if分支,导致count异常累加。
修复:拆分逻辑,先找到最小值再统计次数(避免同时更新min和count的混乱):
public static int[] getMin(int[][] numbers, int actualRows, int actualCols) { int minValue = Integer.MAX_VALUE; int count = 0; // 第一步:找到最小值 for (int i = 0; i < actualRows; i++) { for (int j = 0; j < actualCols; j++) { if (numbers[i][j] < minValue) { minValue = numbers[i][j]; } } } // 第二步:统计最小值出现次数 for (int i = 0; i < actualRows; i++) { for (int j = 0; j < actualCols; j++) { if (numbers[i][j] == minValue) { count++; } } } return new int[]{minValue, count}; }
注意要传入实际有效的行数和列数,避免统计未使用的0值。
完整修正后的代码示例
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; class A1_Part1 { public static void main(String[] args) throws FileNotFoundException { final int SIZE = 10000; int[][] elevations = new int[SIZE][SIZE]; int row = 0; int col = 0; final String filename = "src/ELEVATIONS.TXT"; File file = new File(filename); Scanner fileInput = new Scanner(file); fileInput.useDelimiter(",\\s*"); // 设置分隔符处理逗号 // 填充二维数组 while (fileInput.hasNextInt() && row < SIZE) { elevations[row][col] = fileInput.nextInt(); col++; if (col == SIZE) { row++; col = 0; } } fileInput.close(); // 计算实际有效行数和列数 int actualRows = row; int actualCols = (row == 0) ? col : SIZE; int[] result = getMin(elevations, actualRows, actualCols); System.out.printf("%d is the lowest elevation and appears %d times", result[0], result[1]); } public static int[] getMin(int[][] numbers, int actualRows, int actualCols) { int minValue = Integer.MAX_VALUE; int count = 0; // 查找最小值 for (int i = 0; i < actualRows; i++) { for (int j = 0; j < actualCols; j++) { if (numbers[i][j] < minValue) { minValue = numbers[i][j]; } } } // 统计次数 for (int i = 0; i < actualRows; i++) { for (int j = 0; j < actualCols; j++) { if (numbers[i][j] == minValue) { count++; } } } return new int[]{minValue, count}; } }
内容的提问来源于stack exchange,提问作者Andrew Hayes
相关产品推荐
相关产品推荐

