Tic Tac Toe Board 2d阵列

时间:2013-12-04 23:08:22

标签: java arrays tic-tac-toe

我正在做一个tic tac toe游戏。我写了一个打印板的代码,它为2D数组的空白空间保留下划线括号。有谁知道我最后一行无法打印下划线苞片? Xs和Os存储为字符串“ X ”和“ O ”谢谢!

public void PrintBoard()
{

  System.out.println();
  for (int i = 0; i < board.length; i++)
  {
     for (int j = 0; j < board.length; j++)
     {
        if (board[i][j] == null) 
           System.out.print("___");
        else
           System.out.print(board[i][j]);
        if (j < 2)
           System.out.print("|");
        else
           System.out.println();
     }
  }
  System.out.println();
  }

2 个答案:

答案 0 :(得分:2)

如果在打印下划线之前添加“if(i&lt; 2)”怎么样?

  for (int i = 0; i < board.length; i++)
  {
     for (int j = 0; j < board[i].length; j++)
     {
        if (board[i][j] == null) 
        {
           if (i < 2)
                System.out.print("___");
        }
        else
           System.out.print(board[i][j]);
        if (j < 2)
           System.out.print("|");
        else
           System.out.println();
     }
  }
  System.out.println();

另外,我不喜欢你使用board.length进行内循环;它应该是board [i] .length。

答案 1 :(得分:0)

这一行

for (int j = 0; j < board.length; j++)

应该是

for (int j = 0; j < board[i].length; j++)

另外,我可能会稍微改变循环......

if (j != 0) {
  System.out.print("|");
}
if (board[i][j] == null) 
  System.out.print("___");
else
  System.out.print(board[i][j]);

然后在内循环之后添加println。

相关问题