获取2D数组的最大值

时间:2016-03-15 03:32:40

标签: java arrays for-loop multidimensional-array

因此,我无法想出一个能够返回存储在2D数组中的最大值的函数。我知道我需要一个for循环来迭代2d数组,但我已经失去了

class maximum {
   public static void main(String[] args) {
      int[][] table = { {3, 9, 6, 12},
                        {23, -25, 54},
                        {0, -12, 27, 8, 16} };
      System.out.println(getMax(table));  //prints 54
  }
  static int getMax(int[][] A){


     }
}

1 个答案:

答案 0 :(得分:0)

你知道自己需要什么,就这样做。

static int getMax(int[][] A) {
    int max = 0;
    boolean maxValid = false;
    if (A != null) {
        for (int i = 0; i < A.length; i++) {
            if (A[i] != null) {
                for (int j = 0; j < A[i].length; j++) {
                    if (!maxValid || max < A[i][j]) {
                        max = A[i][j];
                        maxValid = true;
                    }
                }
            }
        }
    }
    if (!maxValid) throw new IllegalArgumentException("no elements in the array");
    return max;
}