我试图编写一种方法,使人们能够通过扫描仪输入整数,而不会因异常而导致程序崩溃。这是我最初拥有的:(这里,sc 是一个 Scanner 对象)
public static int inputInt(String message) {
int returnval = 0;
System.out.println(message);
try {
returnval = sc.nextInt();
} catch (Exception ex) {
System.out.println("You must enter an integer.");
inputInt(message);
}
return returnval;
}
当我使用无效输入测试程序时,启动了无限循环,并在 Eclipse 停止之前多次打印消息和“您必须输入整数”。 我使用以下代码修复了此问题:
public static int inputInt(String message) {
int returnval = 0;
System.out.println(message);
String valstring = sc.nextLine();
try {
returnval = Integer.parseInt(valstring);
} catch (Exception ex) {
System.out.println("You must enter an integer.");
inputInt(message);
}
return returnval;
}
为什么第一种方法失败,而第二种方法却失败?可能有更干净的方法来实现这一点吗?
最佳答案
是的,有一个更简洁的方法:使用hasNextInt
:
public static int inputInt(String message) {
System.out.println(message);
while (!sc.hasNextInt()) {
sc.nextLine(); // clear the bad input first
System.out.println("You must enter an integer.");
System.out.println(message); // why use recursion? just use a while loop
}
return sc.nextInt();
}
我所做的改变:
- 使用
hasNextInt
,因此您不必使用异常 - 添加了
sc.nextLine();
(问题的根源) - 不使用递归,只执行 while 循环(既然可以简单循环,为什么还要递归?)
- 消除临时变量
- 使其更具可读性(IMO)
关于java - 由于递归而导致无限循环(介绍性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21009751/