Java递归方法中使用Scanner对象返回异常值的问题排查
问题分析与解决方案
核心问题:递归调用未返回结果
你的代码在ERROR1、ERROR2分支里调用readUserColumn()时,没有用return返回递归调用的结果。比如:
当你第一次输入非数字触发ERROR2分支,递归调用方法后用户输入了合法数字,此时递归方法会返回正确的column,但上层的原方法会继续执行到最后的return 100,最终返回的就是100而非正确值。
次要问题:重复创建Scanner与未清理无效输入
- 每次递归都新建
Scanner实例完全没必要,还可能引发输入流的异常行为,应该复用同一个Scanner。 - 输入非数字时,
scanner.hasNextInt()为false,这时候必须把缓冲区里的无效输入读取并丢弃,否则下次调用hasNextInt()仍会检测到同一个无效输入,陷入死循环。
修正后的代码
// 建议把Scanner声明为类成员变量,避免重复创建 // 比如:private Scanner scanner = new Scanner(System.in); private int readUserColumn() { System.out.println("Enter value"); if (scanner.hasNextInt()) { int column = scanner.nextInt(); if (_variants.contains(column)) { return column; } else { System.out.println("ERROR1:输入不在1-3范围内"); printMatrix(); return readUserColumn(); // 递归调用时返回结果 } } else { System.out.println("ERROR2:请输入数字"); scanner.next(); // 读取并丢弃无效输入,清理缓冲区 return readUserColumn(); // 递归调用时返回结果 } // 这里无需return 100,所有分支已覆盖返回逻辑 }
额外优化:用循环替代递归
递归多次调用可能引发栈溢出,换成循环更稳定:
private int readUserColumn() { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("Enter value"); if (scanner.hasNextInt()) { int column = scanner.nextInt(); if (_variants.contains(column)) { return column; } else { System.out.println("ERROR1:输入不在1-3范围内"); printMatrix(); } } else { System.out.println("ERROR2:请输入数字"); scanner.next(); } } }
内容的提问来源于stack exchange,提问作者Александр Буйлов
相关产品推荐
相关产品推荐

