求助:Java井字棋程序输入≥9数值或重复位置时崩溃的解决方案
井字棋输入异常修复方案
核心问题分析
输入≥9的数值时程序崩溃,本质是直接将输入值作为数组索引使用(井字棋棋盘对应1-9位置,数组索引通常为0-8),输入≥9会触发数组越界异常(ArrayIndexOutOfBoundsException)。
具体修复步骤
1. 增加输入范围与格式校验
在获取用户输入后,先校验输入是否为整数、是否在1-9区间内,不符合则提示重新输入:
Scanner scanner = new Scanner(System.in); int position; do { System.out.print("请输入1-9之间的位置:"); // 过滤非数字输入 while (!scanner.hasNextInt()) { System.out.println("请输入有效的数字!"); scanner.next(); // 清空无效输入缓存 } position = scanner.nextInt(); // 校验输入范围 if (position < 1 || position > 9) { System.out.println("位置无效,请输入1-9之间的数字!"); } // 复用你已有的重复输入校验逻辑 } while ((position < 1 || position > 9) || isPositionTaken(position));
2. 正确转换输入到数组索引
若棋盘用数组存储(如char[] board = new char[9]),需将用户输入的1-9转换为0-8的索引:
int index = position - 1; board[index] = currentPlayer; // currentPlayer为X或O
3. 整合完整校验逻辑
把格式、范围、占用状态校验整合到一个方法,确保只有合法输入才会被处理:
public static int getValidInput(Scanner scanner, char[] board) { int position; while (true) { // 校验输入是否为整数 while (!scanner.hasNextInt()) { System.out.println("请输入有效的数字!"); scanner.next(); } position = scanner.nextInt(); // 校验输入范围 if (position < 1 || position > 9) { System.out.println("位置超出范围,请输入1-9之间的数字!"); continue; } // 校验位置是否已被占用 int index = position - 1; if (board[index] != ' ') { // 假设空位置用空格标识 System.out.println("该位置已被占用,请重新选择!"); continue; } // 所有校验通过,返回合法索引 return index; } }
关键注意点
- 必须对用户输入做三层校验:格式校验(是否为整数)、范围校验(是否在1-9区间)、状态校验(是否已被占用),避免任何非法输入进入核心逻辑。
- 数组索引从0开始,用户输入的位置值必须减1后再作为索引使用,这是避免越界异常的核心操作。
内容的提问来源于stack exchange,提问作者Mero At Last Place
相关产品推荐
相关产品推荐

