使用二维阵列找到列中的最大数目 [英] Finding the largest number in a column using 2D arrays
问题描述
我是想写发现一列中数量最多的方法。但是,似乎,我有问题,找到一种方法,以返回列的最高数量,而不是考虑到结合阵列中的所有数字。我真的AP preciate任何意见或反馈!
这是我的code:
公共静态无效MAX1(INT [] []分数){
的for(int i = 0; I< score.length;我++){
INT最大=得分[0] [0];
对于(INT J = 0; J<比分[I]。长度; J ++)
如果(得分由[i] [j]的>最大)
最大=得分[I] [J]。
的System.out.println(最大值+);
}
}
不要 INT最大=得分[0] [I];
而不是 INT最大=得分[0] [0];
因为如果你用总是intialize最大比分[0] [0]
这INT较大然后在列的最大价值,你会得到一个错误的结果。
和做的:
如果(得分[内环] [outerloop>最大)
最大=得分[内环] [outerloop];
而不是:
如果(得分[outerloop] [内环>最大)
最大=得分[outerloop] [内环];
这是合乎逻辑的失败,因为第一个指数是列和谢胜利是行
比分[0] [0] = 1;
得分[0] [1] = 2;
得分[0] [2] = 3;
评分[1] [0] = 4;
评分[1] [1] = 5;
评分[1] [2] = 6;
得分[2] [0] = 7;
得分[2] [1] = 8;
得分[2] [2] = 9;
该阵列现在这个样子矩阵:
1 2 3
4 5 6
7 8 9
您想这样你HABE比较比较,例如1,4,7 比分[0] [0]
,比分[0] [ 1]
,比分[0] [2]
。因此谢胜利索引必须是内for循环的计数器。
I was trying to write a method that finds the largest number in a column. However, it seems that I am having problem to find a way to return the highest number in a column rather than taking into consideration all numbers combined in the array. I would really appreciate any comments or feedback!
This is my code:
public static void max1(int[][] score) {
for (int i = 0; i < score.length; i++) {
int max = score[0][0];
for (int j = 0; j < score[i].length; j++)
if (score[i][j] > max)
max = score[i][j];
System.out.println(max + " ");
}
}
Do int max = score[0][i];
instead of int max = score[0][0];
Because if you always intialize max with score[0][0]
and this int is bigger then the biggest value in a column, you will get a wrong result.
And do:
if (score[innerloop][outerloop] > max)
max = score[innerloop][outerloop];
instead of:
if (score[outerloop][innerloop] > max)
max = score[outerloop][innerloop];
That was logical failure because the first index is the column and the secound is the row.
score[0][0] = 1;
score[0][1] = 2;
score[0][2] = 3;
score[1][0] = 4;
score[1][1] = 5;
score[1][2] = 6;
score[2][0] = 7;
score[2][1] = 8;
score[2][2] = 9;
The Array now look like this matrix:
1 2 3
4 5 6
7 8 9
You want compare for example 1,4,7 so you habe to compare score[0][0]
, score[0][1]
, score[0][2]
. So the secound index must be the counter of the inner for-loop.
这篇关于使用二维阵列找到列中的最大数目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!