[英]Getting max value of a 2D array
So, I am having trouble coming up with a function that will return the maximum value stored in a 2D array. 因此,我很难提出一个函数,该函数将返回存储在2D数组中的最大值。 I know I need a for loop to iterate through the 2d array, but I'm so lost
我知道我需要一个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){
}
}
You know what you need, so do it. 您知道自己需要什么,就去做。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.