gpt4 book ai didi

java - 如何从二维数组中查找索引

转载 作者:行者123 更新时间:2023-12-03 02:19:40 25 4
gpt4 key购买 nike

我想做的是打印二维数组中的最大数字及其索引位置。我能够找到最大的数字,但我似乎不知道如何打印它的索引位置。无论如何,这是我到目前为止所拥有的:

public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};

double max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];

}
}
}
System.out.println(max);
System.out.println(i + j); //No idea what I should be doing here, just trying out everything I can think of

最佳答案

现在,您应该始终获得 2 * arr.length 作为最终值。这可能不是您正在寻找的。看起来您想知道最大值的坐标。为此,您需要缓存索引的值,然后在以后使用它们:

public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int tmpI = 0;
int tmpJ = 0;
double max = arr[0][0];
// there are some changes here. in addition to the caching
for (int i = 0; i < arr.length; i++) {
int[] inner = arr[i];
// caches inner variable so that it does not have to be looked up
// as often, and it also tests based on the inner loop's length in
// case the inner loop has a different length from the outer loop.
for (int j = 0; j < inner.length; j++) {
if (inner[j] > max) {
max = inner[j];
// store the coordinates of max
tmpI = i; tmpJ = j;
}
}
}
System.out.println(max);
// convert to string before outputting:
System.out.println("The (x,y) is: ("+tmpI+","+tmpJ+")");

关于java - 如何从二维数组中查找索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7535556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com