学习中遇到的一个小题目:遍历二维数组,获取元素中的最大值和下标。代码如下:
package test;
import java.util.Arrays;
public class Test6 {
public static void main(String[] args) {
int[][] arr1 = new int[5][5];
//生成随机数数组
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
arr1[i][j] = (int)(Math.random() * 100);
}
}
//打印数组,方便结果验证
for (int i = 0; i < arr1.length; i++) {
System.out.println(Arrays.toString(arr1[i]));
}
Location location = locateLargest(arr1);
System.out.println("最大值是:" + "arr1[" + location.row + "][" + location.column + "]=" + location.maxValue);
}
//该方法返回的对象包含了最大值以及最大值的下标
public static Location locateLargest(int[][] arr) {
Location location = new Location();
int row = 0;
int column = 0;
int maxValue = 0;
//遍历数组,获取元素中的最大值及其定位
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxValue) {
row = i;
column = j;
maxValue = arr[i][j];
}
}
}
location.row = row;
location.column = column;
location.maxValue = maxValue;
return location;
}
}
class Location {
public int row;
public int column;
public int maxValue;
}