2016-05-10 58 views
0

我正在關注tutorial在線,而且我有麻煩理解那裏寫的代碼。我應該如何理解瓷磚地圖中的「for」語句?

public Tilemap() { 
    int[][] tilemap = new int[30][50]; 

    System.out.println("New Tilemap created."); 
    Random r = new Random(); 

    int rows = tilemap.length; 
    int columns = tilemap[1].length; 

    printTiles(rows, columns, tilemap, r); 
} 

public void printTiles(int rows, int columns, int[][] tilemap, Random r) { 
    for (int i = 0; i < rows; i++) { 
     for (int j = 0; j < columns; j++) { 
      tilemap[i][j] = r.nextInt(5); 
      System.out.print(" " + tilemap[i][j]); 
     } 

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

我明白了一切,直到for聲明:

for (int i = 0; i < rows; i++) { 
     for (int j = 0; j < columns; j++) { 
      tilemap[i][j] = r.nextInt(5); 
      System.out.print(" " + tilemap[i][j]); 
     } 

     System.out.println(" "); 
    } 

本教程沒有解釋關於他們的一位。所以如果有人能幫助我理解,for聲明中大部分行的目的是什麼,我會很感激。

回答

1

它看起來像遍歷整個二維數組,並在每個索引處放置隨機整數。

我評論過下面的代碼。希望這可以解釋它。

for (int i = 0; i < rows; i++) { //iterate through every row 
     for (int j = 0; j < columns; j++) { //iterate through every column 
      tilemap[i][j] = r.nextInt(5); //place an integer between 0 (inclusive) and 5 (exclusive) at the specified location in the 2d array 
      System.out.print(" " + tilemap[i][j]); //print the integer that was just placed with a preceding space 
     } 

     System.out.println(" "); //print a new line since we've reached the end of the row 
    } 
+0

謝謝你的幫助。 –

+0

不客氣。 – tnw

+0

哦,還有一個問題。這條線意味着什麼:'int columns = tilemap [1] .length;'?這些列是從'1'索引生成的? –