打印并计算2d数组java中的最大值

打印并计算2d数组java中的最大值,java,Java,我有2d数组java,我需要查看它并检查最大值,然后用数组中的数量打印它 我试着这样做,但没用 int[]rand=new int[]{ {1, 80, 3, 4, 5}, {13, 199, 80, 8}, {12, 22, 80, 190} }; int max=rand[0][0]; 整数计数=0; 对于(int i=0;i

我有2d数组java,我需要查看它并检查最大值,然后用数组中的数量打印它

我试着这样做,但没用

int[]rand=new int[]{
{1, 80, 3, 4, 5},
{13, 199, 80, 8},
{12, 22, 80, 190}
};
int max=rand[0][0];
整数计数=0;
对于(int i=0;i最大值){
max=兰特[i][ii];
计数++;
}
}
}

系统输出打印项次(最大+计数)您没有正确处理计数:

int max = rand[0][0];
int count = 0
for (int i = 0; i < rand.length; i++){
    for (int ii = 0; ii < rand[i].length; ii++) {
        if (rand[i][ii] > max) {
            max = rand[i][ii];
            count = 1; // a new maximum's first occurrence
        } else if (rand[i][ii] == max) {
            count++; // another occurrence of the current maximum
        }
    }
}
System.out.println(max + " " + count);
编辑:

修复了第一个元素为最大值的情况。事实证明,
count
毕竟应该初始化为
0
,因为循环会重新访问第一个元素,所以如果它是最大值,我们不希望计数两次。

您可以使用流:

    int max = Arrays.stream(rand)
            .mapToInt(row -> Arrays.stream(row).max().getAsInt())
            .max().getAsInt();

    int count = Arrays.stream(rand)
            .mapToInt(row -> (int) Arrays.stream(row).filter(i-> i==max).count())
            .reduce(Integer::sum).getAsInt();

您所处的路径是正确的,但每次发现较大的值时,都需要重置计数。这意味着您还需要一个if语句,该语句表示如果值等于max,则增加count。因此,在代码中,它表示count++do count=1,然后添加一个else if语句以增加count。此外,如果值等于maxIn,则可能需要处理空数组。语句
rand[0][0]
将在空数组上引发OutOfBoundsException。这是不正确的解决方案。尝试使用int[][]rand=newint[][{200,80199199199,5},{13199,80,8},{12,22,80200}@亚历山大:哦,你说得对
count
毕竟应该初始化为0。@Eran-我们几乎同时发布了答案,但当我看到你的答案时,我甚至没有意识到你犯了那个错误,为了纪念像你这样伟大的人,我删除了没有这个错误的答案
    int max = Arrays.stream(rand)
            .mapToInt(row -> Arrays.stream(row).max().getAsInt())
            .max().getAsInt();

    int count = Arrays.stream(rand)
            .mapToInt(row -> (int) Arrays.stream(row).filter(i-> i==max).count())
            .reduce(Integer::sum).getAsInt();