首页 > 解决方案 > 井字游戏输出

问题描述

我正在做一个井字游戏任务,但我的棋盘并没有如我所愿。我附上了一张我希望我的董事会喜欢的图片以及我需要帮助的代码部分。

在此处输入图像描述

我认为错误出在这部分代码中:

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();
}

标签: javaarraysascii-art

解决方案


在我看来很好。

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 |   |   |   |
   |---|---|---|

推荐阅读