java如何找到数组索引的位置和最小值?
我如何通过添加数组的最小值来完成这个程序,以及最小值的位置
public static void main(String[] args) {
Scanner input;
/* A file for the program to open, the absolute location is based on
* the location of the project. /src/array2d/ locates the file in
* the current source folder
*/
File fileIn = new File("src/array2d/array2dtest1.txt");
// You can fetch the full absolute path with the method below
// System.out.println(fileIn.getAbsolutePath());
/* try...catch is necessary for reading files, as it is possible that
* the file does not exist.
*/
try {
//creating a scanner from the file, rather than using console.
input = new Scanner(fileIn);
}
catch (FileNotFoundException e) {
// if file is not found, terminate the program
System.out.println(fileIn.getName() + " is not found.");
return;
}
int row = input.nextInt();
int column = input.nextInt();
int [][] arr = new int[row][column];
int [] min = arr[0];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
arr[i][j] = input.nextInt();
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
int k;
k = arr[i][j];
System.out.printf(" %3d", k );
}
System.out.println();
}
input.close();
//min
int i;
for(i = 1; i < arr.length; i++) {
if(i == 1)
min = arr[i];
}
System.out.printf(" min: " + min);
}
输出应为:
39 95 99 56 41
88 8 1 48 75
3 58 13 54 80
92 72 74 25 86
30 38 3 21 2
最小值为1,其位置为(无论位置如何)
# 1 楼答案
这里为您提供了一个新的
min
循环,它被塞进了同时处理行和列的循环中,还为字符串提供了一些更好的格式:)另外,删除顶部的
min
声明如果你愿意的话,你可以更干净一些,把所有的声明移到类的顶部,但我不想再把事情搞得一团糟,只保留一小部分更改