簡體   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