简体   繁体   中英

Tic Tac Toe Board - Java

I was trying to write a code for Tic Tac Toe Game. I wrote the following code to display the board of the game but something is wrong and it isn't displaying the required output. Could you please help me figure out where the mistake is?

Here:

0 represents blank ,

1 represents X and

2 represents 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");
        }
    }
}

Output:

输出图像

You forgot your break; s in your switch statement, try:

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;

You need a break (and maybe a tabulator character to get the same distance in the signs)

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM