【问题标题】:Tic Tac Toe Board - Java井字游戏板 - Java
【发布时间】:2016-06-14 01:11:30
【问题描述】:

我正在尝试为井字游戏编写代码。我编写了以下代码来显示游戏的棋盘,但是出了点问题,它没有显示所需的输出。你能帮我找出错误在哪里吗?

这里:

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

输出:

【问题讨论】:

  • 真的很遗憾你刚刚删除了关于偶数的 c++ 问题。 . .无论如何,这是您的解决方案:pastebin.com/jdTAwaG4

标签: java


【解决方案1】:

你在你的 switch 语句中忘记了你的break;s,试试:

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;

【讨论】:

    【解决方案2】:

    您需要休息一下(可能需要一个制表符才能在标志中获得相同的距离)

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

    【讨论】:

      猜你喜欢
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多