Tic Tac Toe Board - Java

时间:2016-06-13 16:00:41

标签: java

我正在尝试为Tic Tac Toe Game编写代码。我编写了以下代码来显示游戏的主板,但是有些不对劲并且它没有显示所需的输出。你能帮我弄清楚错误在哪里吗?

下面:

0表示空白

1代表X

2表示O

public class Trying
{
    public static void main(String[] args) {

    int board[][] = {{1,0,2},
                    {0,1,0},
                    {0,2,0}};

        for(int row = 0; row<3; row++)
        {
            for(int col = 0; col<3; col++)
            {
                printCell(board[row][col]);
                if(col<2)
                {
                    System.out.print(" | ");
                }
            }
            System.out.println("\n------------");
        }
    }

    public static void printCell(int content){
        switch(content){
            case 0: System.out.print(" ");
            case 1: System.out.print("X");
            case 2: System.out.print("O");
        }
    }
}

输出:

Image of the output

2 个答案:

答案 0 :(得分:4)

您在switch语句中忘记了break;,请尝试:

public static void printCell(int content){
    switch(content){
        case 0: System.out.print(" ");
            break;
        case 1: System.out.print("X");
            break;
        case 2: System.out.print("O");
            break;
    }
}

Read here for why we need break;

答案 1 :(得分:1)

你需要一个休息时间(也许是制表符,以便在标志中获得相同的距离)

public static void main(String[] args) {

    int board[][] = { { 1, 0, 2 }, { 0, 1, 0 }, { 0, 2, 0 } };

    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            printCell(board[row][col]);
            if (col < 2) {
                System.out.print("|");
            }
        }
    }
    System.out.println("\n--------------------------------------------");
}

public static void printCell(int content) {
    switch (content) {
        case 0:
            System.out.print("\t \t");
            break;
        case 1:
            System.out.print("\tX\t");
            break;
        case 2:
            System.out.print("\tO\t");
            break;
    }
}

enter image description here