java - 井字游戏输出
问题描述
我正在做一个井字游戏任务,但我的棋盘并没有如我所愿。我附上了一张我希望我的董事会喜欢的图片以及我需要帮助的代码部分。
我认为错误出在这部分代码中:
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();
}
输出:
1 2 3
|---|---|---|
A | | | |
|---|---|---|
B | | | |
|---|---|---|
C | | | |
|---|---|---|
推荐阅读
- java - 在JAVA中,线程通知后,它立即执行什么?等待锁或 cpu 调度
- c# - 使用 CreateUploadSesssion 上传文件时服务器返回代码:InternalServerError
- excel - OfficeJs - 获取 excel/powerpoint 文件的字体/主题颜色
- python - 使用 pygame 加载图像
- blazor - Blazor 服务器端 (.Net Core) 自定义菜单
- python - 如何加速 Matplotlib 动画?
- compilation - Fortran Compiler Optimization
- typescript - 当我在 VS 代码编辑器上保存代码时,自动更改代码格式
- python - Python 日志记录 - 覆盖“记录”中的 args/msg 以避免更改为可变对象数据
- powershell - Powershell 4 对于 tls 1.2 来说太旧了?