简体   繁体   中英

How to loop 2D array using for-loop?

Looking at a for-each loop but don't know how to do it using regular for loop in Java as in:

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

Change this for-each loop

    for (int[] bomb: bombs) {

Tried this

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

Clarification: I know what these two loops mean

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

If possible, I want their combined functionality of saving the i position in 2D array and saving i as the array itself in one for loop line. In other words, I want the convenience of having the loop position in 2D array and directly grabbing the int[] array in the 2D array.

Context

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;
    }
 }

As per The for Statement following two are the same:

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

or

for (int[] bomb : bombs) {

}

Assuming that I understand your question, just use two, nested for-each style loops; one for the double array and one for each member of the double array. Here is some example code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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