繁体   English   中英

如何使用for循环循环2D数组?

[英]How to loop 2D array using for-loop?

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

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

为每个循环改变这个

    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循环线中。 换句话说,我想方便在2D数组中使用循环位置并直接获取2D数组中的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;
    }
 }

根据以下两个相同的声明

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

要么

for (int[] bomb : bombs) {

}

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

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("} ");
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM