所以,我在想出一个返回二维数组中存储的最大值的函数时遇到了困难。我知道我需要一个 for 循环来迭代二维数组,但我迷失了
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){
}
}
最佳答案
你知道自己需要什么,那就去做吧。
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;
}
关于java - 获取二维数组的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002220/