Java - 列多数组中的最大数字

时间:2015-02-02 11:44:42

标签: java arrays multidimensional-array

似乎我在以下代码中超出界限(请参阅注释行),我似乎无法解决问题。我在这里忽略或忘记了什么吗?

int[][] num = {   {10,2,5},
                  {5,1,0},
                  {25,35,16,20,19},
                  {26,27,100} };

for (int col = 0; col < num.length; col++) {
    int highest = Integer.MIN_VALUE;
    for (int row = 0; row < num[col].length + 1; row++)
        if (num[row][col] > highest) //this is where I get the error.
            highest = num[row][col];
    System.out.println( "Highest number in column " + col + " = " + highest);
}

4 个答案:

答案 0 :(得分:2)

// Ok, first find the longest row:
int longest = Integer.MIN_VALUE;
for (int[] row : num) {
    longest = Math.max(longest, row.length);
}

// then, create an array to store max column values:
int[] rowHigh = new int[longest];
for (int i = 0; i < longest; i++) {
    rowHigh[i] = Integer.MIN_VALUE;
}

// then iterate over initial array to find max values of each column
for (int[] row : num) {
    for (int i = 0; i < row.length; i++) {
        rowHigh[i] = Math.max(rowHigh[i], row[i]);
    }
}

答案 1 :(得分:0)

为了找到每列的最大数量,首先必须找到最长的行,以便知道外循环的范围:

int longestRow = 0;
for (int row = 0; row < num.length; row++)
    if (num[row].length > longestRow)
        longestRow = num[row].length;

然后你可以迭代每一列,但你必须检查你到达的每一行当前列是否存在于该行中:

for ( int col = 0; col < longestRow; col++)
{
   int highest = Integer.MIN_VALUE;
   for ( int row = 0; row < num.length; row++)
        if ( col < num[row].length && num[row][col] > highest) 
            highest = num[row][col];
    System.out.println( "Highest number in column " + col + " = " + highest);
}

输出:

Highest number in column 0 = 26
Highest number in column 1 = 35
Highest number in column 2 = 100
Highest number in column 3 = 20
Highest number in column 4 = 19

答案 2 :(得分:0)

在2D数组中,与你的num [a] [b]一样,array.length给出行数。 获取row [i]中的列数使用:array [i] .length。即获取第i行中的列数

使用以下代码:         int [] [] num = {{10,2,5},                 {5,1,0},                 {} 25,35,16,20,19,                 {26,27,100}};

    int highest = Integer.MIN_VALUE;
    int row = 0 ,col = 0;
     for ( row = 0; row < num.length; row++ )
     {
         for ( col = 0; col < num[row].length; col++ )
             if (num[row][col] > highest )
                 highest = num[row][col];
     }
     System.out.println( "Highest number in row:"+row+" column:" + col + ". Highest value is: " + highest );

答案 3 :(得分:0)

使用Java 8

int[][] num = {{10, 2, 5},
        {5, 1, 0},
        {25, 35, 16, 20, 19},
        {26, 27, 100}};


int max = Stream.of(num) // give me a stream of int[]
                // unpack those int[] into an IntStream
                .flatMapToInt(arr -> IntStream.of(arr))
                // find the maximum.
                .max()
                // as a plain int value.
                .getAsInt();
System.out.println(max);