我创建了一个类,目的是使用它在奥赛罗游戏的屏幕上打印 8 x 8 的游戏板。我的游戏板在侧面打印有字母,但是我无法弄清楚如何在板的顶线上方打印字母。
这是迄今为止的类代码:
public class CreateBoard {
public char[][] board;
public CreateBoard(){
board = new char[8][8];
}
public void printBoard(){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = '-';
}
}
for(int i = 0; i < board.length; i++){
System.out.println();
for(int j = 0; j < board.length; j++){
if(j == 0){
System.out.print(i + 1);
System.out.print("| ");
}
System.out.print(board[i][j] + " | ");
}
}
}
那么,实现顶行上方数字的正确方法是什么?提前致谢。
当前的输出如下:
这是我想要的样子:
最佳答案
在打印棋盘之前添加一个 for 循环来打印字符。
public void printBoard(){
System.out.print(" ");//beginning 2 spaces
for(int i = 0; i < board.length; ++i)
System.out.print(" " + (char)(i + 'A') +" ");//print letters seperately.
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = '-';
}
}
for(int i = 0; i < board.length; i++){
System.out.println();
for(int j = 0; j < board.length; j++){
if(j == 0){
System.out.print(i + 1);
System.out.print("| ");
}
System.out.print(board[i][j] + " | ");
}
}
}
关于java - 将字母添加到打印有嵌套 for 循环的游戏板顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33931160/