我正在为我正在参加的课程研究数据结构和算法问题。
我被要求将一个 .txt 文件的内容放入一个二维数组中,并找到最小值及其在数组中出现的次数。 .txt文件包含大量0000-120000的数字集合
29432、113244、96324...等等
这是我的代码。
class A1_Part1 {
public static void main(String[] args) throws FileNotFoundException {
final int SIZE = 10000;
int count = 0;
int[][] elevations = new int[SIZE][SIZE];
final String filename = "src/ELEVATIONS.TXT";
File file= new File(filename);
Scanner fileInput = new Scanner(file);
while (fileInput.hasNextLine() && count < elevations.length) {
elevations[count][0] = fileInput.nextInt();
// System.out.println(Arrays.deepToString(elevations));
count++;
}
int[][] numbers = Arrays.copyOf(elevations, count);
fileInput.close();
int[] result = getMin(numbers);
System.out.printf("%d is the lowest elevation and appears %d times",
+result[0], result[1]);
}
public static int[] getMin(int[][] numbers) {
int minValue = numbers[0][0];
int count = 0;
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length ; j++) {
if (numbers[i][j] < minValue)
minValue = numbers[i][j];
else if (numbers[i][j] == minValue)
count++;
}
}return new int[]{minValue, count};
}
当我运行程序时,我得到答案 0 和 999999999。 我意识到我只得到最小值为 0 的结果,因为当我使用 Arrays.deepToString 方法打印数组时,我只得到数百万个 0。看起来代码只是在制作一个充满 1 亿个 0 的空白数组。
我一直在尝试很多不同的方法来解决这个问题,但我无法将文件的内容放入数组中以使用 getMin 方法进行处理。我认为 while 循环会遍历数组并将 .txt 文件的值添加到海拔数组,但它没有这样做。
我不允许使用 ArrayList 来解决这个问题,因此我在 main 方法中使用 count 和 arrays.copyOf 来获取数组的实际大小。
我错过了什么?