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.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;
}

 

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值