【发布时间】:2019-06-02 07:47:01
【问题描述】:
正在查看 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 位置保存在 2D 数组中,并将 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;
}
}
【问题讨论】:
-
java中没有花哨的循环;仅循环索引和 for-each。
-
通过搜索“花式增强”循环您期望什么?
-
我想要一个 for 循环,它抓取 int[] 炸弹并使用 i++ 以 for(int i = 0...) 的格式迭代 int[][]bombs,以便我知道它是哪一个得到了
标签: java arrays for-loop foreach