iloveka12 2013-11-26 01:58 采纳率: 0%
浏览 1010

[java] 制作tictactoe 一問

public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    char [] a ={'0','1','2','3','4','5','6','7','8','9'};
   int choice;
   for (int i=1 ; i<8 ; i++) {
   System.out.println(a[1] + " | " + a[2] + " | " +a[3]);
   System.out.println(a[4] + " | " + a[5] + " | " +a[6]);
   System.out.println(a[7] + " | " + a[8] + " | " +a[9]);
   if (a[i]%2==1) {
   System.out.print("Player X input the position (1-9) :");
   choice=input.nextInt();
   a[choice]= 'X'; }
   else  {
   System.out.print("Player O input the position (1-9) :");
   choice=input.nextInt();
   a[choice]= 'O';  }
   }
   }
}

显示结果为何会输出两个player o
run:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Player X input the position (1-9) :3
1 | 2 | X
4 | 5 | 6
7 | 8 | 9
Player O input the position (1-9) :2
1 | O | X
4 | 5 | 6
7 | 8 | 9
Player O input the position (1-9) :

  • 写回答

1条回答 默认 最新

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-12-08 23:19
    关注

    所有内容均由人工智能模型输出,其内容的准确性和完整性无法保证,不代表我的态度或观点。
    (通义千问专栏,V2.1.0版本,2023.12.01)


    该回答引用通义千问大模型,仅提供参考,不保证完全正确
    问题出在你的for循环里。你用的是i<8,这会导致循环执行7次。而在每次循环中,你都会询问玩家输入一个位置并更新数组,这意味着每个玩家将轮流进行6次操作,而不是3次。


    要修复这个问题,你可以将for循环更改为以下内容:

    int playerTurn = 1; // 初始化为1表示X先手
    boolean gameRunning = true;
    while (gameRunning) {
        System.out.println(a[1] + " | " + a[2] + " | " + a[3]);
        System.out.println(a[4] + " | " + a[5] + " | " + a[6]);
        System.out.println(a[7] + " | " + a[8] + " | " + a[9]);
    
        if (playerTurn % 2 == 1) {
            System.out.print("Player X input the position (1-9) :");
            choice = input.nextInt();
            a[choice - 1] = 'X';
        } else {
            System.out.print("Player O input the position (1-9) :");
            choice = input.nextInt();
            a[choice - 1] = 'O';
        }
    
        playerTurn++;
    
        // 检查游戏是否结束(例如,所有格子都已填满或有玩家获胜)
        // 如果游戏结束,将gameRunning设置为false以退出循环
    
    }
    

    这个修改后的代码会一直循环,直到游戏结束。你需要添加一些额外的逻辑来检查游戏是否结束,比如所有的格子都被填满了或者有玩家获胜。如果满足这些条件之一,你应该将gameRunning设置为false以退出循环。

    评论

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号