Java:⼆维数组的最⼤值和下标学习中遇到的⼀个⼩题⽬:遍历⼆维数组,获取元素中的最⼤值和下标。代码如下:
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.String(arr1[i]));
}
Location location = locateLargest(arr1);
System.out.println("最⼤值是:" + "arr1[" + w + "][" + lumn + "]=" + 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.maxValue = maxValue;
return location;
}
}
class Location {
public int row;
public int column;
public int maxValue;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论