【问题标题】:How to loop 2D array using for-loop?如何使用for循环循环二维数组?
【发布时间】: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 arrays for-loop foreach


【解决方案1】:

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

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

for (int[] bomb : bombs) {

}

【讨论】:

  • Op 询问的是普通方式而不是增强方式。 “如何在数组数组中循环正常方式”
  • 你能在 for 循环中使用 int[] i 来代替常规的 int 吗?
  • 但是你能不能用 in[]i 和一个计数器进行迭代,比如 for (int[] i =0; i
  • @PL 我很难理解问题出在哪里。使用for 循环有两种主要方法,仅此而已。如果您需要额外的计数器,请使用for (int i ...
  • @CommonMan 两个版本都显示为等效,因此 OP 在这里得到了答案。
【解决方案2】:

假设我理解您的问题, 只需使用两个嵌套的 for-each 样式循环; 一个用于双精度数组,一个用于双精度数组的每个成员。 下面是一些示例代码:

public class LearnLoopity
{
  private int[][] doubleListThing = {{0, 0}, {0, 1}, {1, 2}};

  @Test
  public void theTest()
  {
    System.out.print("{");

    for (int[] singleListThing : doubleListThing)
    {
      System.out.print("{");
      for (int individualValue : singleListThing)
      {
        System.out.print(individualValue + " ");
      }

      System.out.print("} ");
    }

    System.out.print("} ");
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2013-09-18
    • 2016-01-20
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多