2016-07-23 149 views
0

工作在井字遊戲。爲什麼我不能打印我的2D陣列?

我一直在努力找出打印2d陣列的正確方法。這是我目前正在處理的方法。試圖打印板內的元素(或值,不管)。這裏有什麼問題?

// display board indicating positions for token (x, o) placement 

public void printBoard(int size) { 
    int col, row; 

    for (col = 0; col < size; col++) 
     System.out.print(" " + col); 
     for (row = 0; row < size; row++) { 
      System.out.print("\n" + row); 
      System.out.print(" " + board[col][row] + "|"); 
      System.out.print(" _ _ _ _ _ _"); 
     } 
} 
+0

您是否錯過了代碼片段中尾部的'}'? –

回答

1

假設尺寸是board.length,問題出在條件的邏輯在內部for循環。 board.length只是您的二維數組中的行數。因此,除非行數等於列數,否則您的代碼將無法工作。 2d數組中的列數等於2d數組中的特定數組或行中的元素數,可以寫爲board [i] .length(i是從0到board.length - 1的數字)。所以我會更新你的方法取兩個參數,而不是一個,

public void printBoard(int rows, int columns) { 

    for (int i = 0; i < columns; i++){ 
     System.out.print(" " + i); 
     for (j = 0; j < rows; j++) { 
      System.out.print("\n" + j); 
      System.out.print(" " + board[j][i] + "|"); 
      System.out.print(" _ _ _ _ _ _"); 
     } 
    } 
} 

然後當你調用只要你做到這一點的方法,

printBoard(board.length, board[0].length); 

注意上面只如果工作二維數組具有相同大小的列。

編輯:確保您的嵌套for-loops使用大括號{}正確格式化,因爲您的外部for循環缺少一對大括號。

0

您忘記給for循環提供{}。當一個循環有多條線時,您必須附上這些語句{}

public void printBoard(int size) { 
     int col, row; 

     for (col = 0; col < size; col++){//here starts { 
      System.out.print(" " + col); 
      for (row = 0; row < size; row++) { 
       System.out.print("\n" + row); 
       System.out.print(" " + board[col][row] + "|"); 
       System.out.print(" _ _ _ _ _ _"); 
      } 
     }// here ends } 
    }