[英]Tic-Tac-Toe board output
我正在做一個井字游戲任務,但我的棋盤並沒有如我所願。 我附上了一張我希望我的董事會喜歡的圖片以及我需要幫助的代碼部分。
我認為錯誤出在這部分代碼中:
public void printBoard() {
char a = 'A';
char b = 'B';
char c = 'C';
System.out.println(" 1 2 3 ");
System.out.println(" ");
for (int i = 0; i < board.length; i++) {
if (i == 0)
System.out.print(" " + a + ' ');
else if (i == 1)
System.out.print(" " + b + ' ');
else if (i == 2)
System.out.print(" " + c + ' ');
for (int j = 0; j < board[i].length; ++j) {
System.out.print("|");
System.out.print(" " + board[i][j] + ' ');
if (j + 1 == board[i].length)
System.out.println("|");
}
System.out.println(" |---|---|---|");
}
System.out.println();
}
在我看來很好。
public static void main(String... args) {
char[][] board = {
{ ' ', ' ', ' ' },
{ ' ', ' ', ' ' },
{ ' ', ' ', ' ' }
};
printBoard(board);
}
public static void printBoard(char[][] board) {
assert board != null;
assert board.length == 3 && board[0].length == 3 && board[1].length == 3 && board[2].length == 3;
System.out.println(" 1 2 3 ");
System.out.println(" |---|---|---|");
for (char row = 0, rowName = 'A'; row < 3; row++, rowName++) {
System.out.print(" " + rowName);
for (int col = 0; col < board[row].length; col++)
System.out.print(" | " + board[row][col]);
System.out.println(" |");
System.out.println(" |---|---|---|");
}
System.out.println();
}
Output:
1 2 3
|---|---|---|
A | | | |
|---|---|---|
B | | | |
|---|---|---|
C | | | |
|---|---|---|
您可以使用畫框字符打印如下內容:
public static void main(String[] args) {
char[][] board = {
{'X', ' ', ' '},
{' ', 'X', ' '},
{' ', ' ', 'O'}};
printBoard(board);
}
public static void printBoard(char[][] board) {
System.out.println(" 1 2 3");
System.out.println(" ┌───┬───┬───┐");
System.out.println("A │ "
+ board[0][0] + " │ "
+ board[0][1] + " │ "
+ board[0][2] + " │ ");
System.out.println(" ├───┼───┼───┤");
System.out.println("B │ "
+ board[1][0] + " │ "
+ board[1][1] + " │ "
+ board[1][2] + " │ ");
System.out.println(" ├───┼───┼───┤");
System.out.println("C │ "
+ board[2][0] + " │ "
+ board[2][1] + " │ "
+ board[2][2] + " │ ");
System.out.println(" └───┴───┴───┘");
}
Output:
1 2 3
┌───┬───┬───┐
A │ X │ │ │
├───┼───┼───┤
B │ │ X │ │
├───┼───┼───┤
C │ │ │ O │
└───┴───┴───┘
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.