I'm working on a tic tac toe game. I wrote a code to print a board, it holds underscore brackets for empty spaces of a 2D array. Does anyone know a way I could not have the underscore bracts print for the last line? Xs and Os are stored as Strings " X " and " O " Thanks!
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();
}
How about adding "if (i<2)" before your print of the underscores?
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();
Also, I don't like your using board.length for the inner loop; it should be board[i].length.
This line
for (int j = 0; j < board.length; j++)
Should be
for (int j = 0; j < board[i].length; j++)
Also, I'd probably change the loop a bit...
if (j != 0) {
System.out.print("|");
}
if (board[i][j] == null)
System.out.print("___");
else
System.out.print(board[i][j]);
And then add a println after that inner loop.
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.