gpt4 book ai didi

java - 如何使用for循环循环二维数组?

转载 作者:行者123 更新时间:2023-11-29 04:12:47 25 4
gpt4 key购买 nike

正在查看 for-each 循环,但不知道如何使用 Java 中的常规 for 循环来实现它,如下所示:

for(int i=0; i<length;i++)

改变这个 for-each 循环

    for (int[] bomb: bombs) {

试过了

`for (int[] bomb = 0; bomb<bombs; bomb++) // doesn't work

澄清:我知道这两个循环是什么意思

for (int[]bomb: bombs)`
for (int i = 0; i<bombs.length; i++){}

如果可能,我想要它们的组合功能,即在二维数组中保存 i 位置并将 i 作为数组本身保存在一个 for 循环行中。换句话说,我想要在二维数组中有循环位置并直接在二维数组中获取 int[] 数组的便利。

上下文

public class MS {
public static void main(String[] args) {
//Example of input
int[][] bombs2 = {{0, 0}, {0, 1}, {1, 2}};
// mineSweeper(bombs2, 3, 4) should return:
// [[-1, -1, 2, 1],
// [2, 3, -1, 1],
// [0, 1, 1, 1]]
}
public static int[][] mineSweeper(int[][] bombs, int numRows, int numCols) {
int[][] field = new int[numRows][numCols];
//////////////////////// Enhanced For Loop ////////////////////
for (int[] bomb: bombs) {
////////////////////// Change to regular for loop //////////////
int rowIndex = bomb[0];
int colIndex = bomb[1];
field[rowIndex][colIndex] = -1;
for(int i = rowIndex - 1; i < rowIndex + 2; i++) {
for (int j = colIndex - 1; j < colIndex + 2; j++) {
if (0 <= i && i < numRows &&
0 <= j && j < numCols &&
field[i][j] != -1) {
field[i][j] += 1;
}
}
}
}
return field;
}
}

最佳答案

根据 The for Statement下面两个是一样的:

for (int i = 0; i < bombs.length; i++) {
int[] bomb = bombs[i];
}

for (int[] bomb : bombs) {

}

关于java - 如何使用for循环循环二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54077885/

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