为什么我不能打印我的2D阵列?

问题描述:

工作在井字游戏。为什么我不能打印我的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

您是否错过了代码片段中尾部的'}'? –

假设尺寸是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循环缺少一对大括号。

您忘记给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 } 
    }