Java 返回二维数组中行的最大值
我目前正在研究一种计算二维数组中每行总和的方法。然而,我有一个特别的问题,我想计算每行绝对值的总和,然后返回4行中的最大值。例如,在我的代码中,下面的最大值是rowTotalTwo,其和为20。纯java和基本javaJava 返回二维数组中行的最大值,java,Java,我目前正在研究一种计算二维数组中每行总和的方法。然而,我有一个特别的问题,我想计算每行绝对值的总和,然后返回4行中的最大值。例如,在我的代码中,下面的最大值是rowTotalTwo,其和为20。纯java和基本java public static void main(String[] args) { int[][] num = {// 0 1 2 3 {4, 6, 9, 3}, {6, 2, 4, 1}, {8
public static void main(String[] args) {
int[][] num = {// 0 1 2 3
{4, 6, 9, 3},
{6, 2, 4, 1},
{8, 3, 7, 9}
};
int[] total = new int[num[0].length];
for (int i=0; i < total.length;i++){
total[i] = 0;
}
for (int i = 0; i < num.length; i++) {
for (int j = 0 ; j < total.length; j++) {
total[j] += num[i][j];
}
}
for (int i=0; i < total.length;i++){
total[i] = Math.abs(total[i]);
}
int max = 0;
for (int i=0; i < num.length;i++){
if (max < total[i])
max = total[i];
}
System.out.println("max : " + max);
}
使用流
int max = Arrays.stream(total).max().getAsInt();
您可以这样做,在这种情况下,您根本不需要修改代码
Math.max(Math.max(Math.abs(rowTotalZero), Math.abs(rowTotalOne)), Math.max(Math.abs(rowTotalTwo), Math.abs(rowTotalThree)));
Math.max(Math.max(Math.abs(rowTotalZero), Math.abs(rowTotalOne)), Math.max(Math.abs(rowTotalTwo), Math.abs(rowTotalThree)));