Java幻方解谜游戏移动操作后幻方不更新问题求助
Java幻方游戏移动无响应问题修复
核心问题:输入解析逻辑错误
getInput方法中使用move.split("")会将输入按单个字符拆分,比如输入3 2 U会被拆分为["3"," ","2"," ","U"],此时array[1]是空格,执行Integer.parseInt(array[1])会抛出异常,进入catch块后checkMove始终为false,导致循环一直重复请求输入,根本无法执行移动逻辑。
修复后的getInput方法
public static int[] getInput(int size) { int row = 0; int col = 0; int dirNum = 0; boolean checkMove = false; Scanner input = new Scanner(System.in); while (!checkMove) { try { System.out.println("Enter a row, column and a direction: U, D, L or R. For example, '3 2 U'. Enter a number from 1 to " + size + " for Row and Column"); String move = input.nextLine().trim(); String[] array = move.split("\\s+"); // 按任意数量空格分割输入 if (array.length != 3) { System.out.println("输入格式错误,请按照示例输入"); continue; } row = Integer.parseInt(array[0]) - 1; col = Integer.parseInt(array[1]) - 1; // 校验行列是否在合法范围内 if (row < 0 || row >= size || col < 0 || col >= size) { System.out.println("行列数字超出范围,请输入1到" + size + "之间的数"); continue; } String direction = array[2].toUpperCase(); switch (direction) { case "U" -> { dirNum = 0; checkMove = true; } case "D" -> { dirNum = 1; checkMove = true; } case "L" -> { dirNum = 2; checkMove = true; } case "R" -> { dirNum = 3; checkMove = true; } default -> System.out.println("方向错误,请输入U/D/L/R"); } } catch (NumberFormatException e) { System.out.println("行列必须是数字,请重新输入"); } catch (Exception e) { System.out.println("输入异常,请重新输入"); } } int[] returnArr = {row, col, dirNum}; return returnArr; }
次要问题1:移动逻辑与输入验证矛盾
原getInput中对方向的限制(比如U要求row>0)和playerMove中的模运算(允许循环到幻方另一侧)冲突,导致合法的循环移动被拒绝。修复时去掉输入验证中的行列限制,让playerMove的逻辑统一处理移动边界。
次要问题2:幻方尺寸输入未循环校验
square.getInput()方法中,用户输入偶数时仅打印提示但仍返回偶数,导致genSquare生成错误的幻方(该方法仅支持奇数尺寸)。修复该方法,强制用户输入正奇数:
static int getInput() { Scanner input = new Scanner(System.in); int n = 0; while (true) { System.out.println("Enter an odd number: "); if (input.hasNextInt()) { n = input.nextInt(); if (n % 2 != 0 && n > 0) { break; } else { System.out.println("The number must be a positive odd integer."); } } else { System.out.println("Please enter a valid integer."); input.next(); // 清除无效输入缓存 } } return n; }
验证说明
修复后,输入3 2 U这类合法指令时,程序会正确解析输入、执行移动操作并更新幻方,循环打印新幻方等待下一次输入,直到幻方恢复原始状态。
内容的提问来源于stack exchange,提问作者romanward78
相关产品推荐
相关产品推荐

