java - 将字母添加到打印有嵌套 for 循环的游戏板顶部

标签 java

我创建了一个类,目的是使用它在奥赛罗游戏的屏幕上打印 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] + " | ");  
        }
    }
}

那么,实现顶行上方数字的正确方法是什么?提前致谢。

当前的输出如下:

enter image description here

这是我想要的样子:

enter image description here

最佳答案

在打印棋盘之前添加一个 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/

相关文章:

Java 给数字添加前导零

java - 在 Java Swing 中停止定时器

java - ActionListener代码触发了两次

java - 具有许多不同 View 的 ListView 适配器

java - 将 Codename One 项目更新到 JDK 8 导致编译错误

java - 如何增加 Vaadin 11.0.0 网格中的行高?

java - 自定义微调器适配器不工作

java - ArrayList不打印所有元素

java - jfreechart XYLineAndShaperanderer、XYDotRenderer 和 XYSplineRenderer 之间的代码差异?

java - 有人可以教我如何解释 javax.net.debug 结果吗?