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以退出循环。

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?