Java TicTacToe游戏问题:添加isGameFinished方法后X无法显示
问题排查与修复
你的代码中,玩家的X标记无法显示的核心问题出在playerMove方法里:当用户输入有效位置时,程序直接跳出循环,完全没调用placeMove方法放置X。
错误代码片段:
private static void playerMove(char[][] board, Scanner scanner) { String userInput; while (true) { System.out.println("Where would you like to play? (1-9)"); userInput = scanner.next(); if (isValidMove(board, Integer.parseInt(userInput))) { break; // 直接跳出循环,未执行放置X的逻辑 } else { System.out.println(userInput + " is not a valid move. Choose another spot"); } placeMove(board, userInput, 'X'); // 仅输入无效时才执行,但此时位置无效也无法放置X } }
修复方案:
将placeMove移到if条件块内部,确认位置有效后再放置X,随后跳出循环:
private static void playerMove(char[][] board, Scanner scanner) { String userInput; while (true) { System.out.println("Where would you like to play? (1-9)"); userInput = scanner.next(); int position = Integer.parseInt(userInput); if (isValidMove(board, position)) { placeMove(board, userInput, 'X'); // 有效位置才执行放置X break; } else { System.out.println(userInput + " is not a valid move. Choose another spot"); } } }
额外补充:
当前的isGameFinished方法仅判断了平局场景,没有检测横/竖/对角线连成三个相同标记的胜负情况,后续需要补充这部分逻辑,否则游戏只会在棋盘填满时结束,无法识别玩家或电脑获胜的情况。
内容的提问来源于stack exchange,提问作者Puddy Dub
相关产品推荐
相关产品推荐

