问题描述
为什么我在递归方法中遇到了无限循环,而没有机会输入任何符号来破坏它?
Why I'm getting infinite loop in recursion method, without a chance to input any symbol to break it?
class Test {
int key=0;
void meth(){
System.out.println("Enter the number here: ");
try(Scanner scan = new Scanner(System.in)) {
key = scan.nextInt();
System.out.println(key+1);
} catch(Exception e) {
System.out.println("Error");
meth();
}
}
}
class Demo {
main method {
Test t = new Test();
t.meth();
}
}
如果您尝试创建错误(将字符串值放入键中,然后尝试向其添加数字),则您将在控制台中获得无限的错误"文本,取而代之的是,在出现第一个错误之后,程序应再次询问数字,然后才决定要做什么.
If you try to create an error (putting string value in key and then try to add to it a number), you will get infinite "Error" text in console, instead of that, after first error, program should ask again the number and only then decide what to do.
推荐答案
如果nextInt()
失败,它将引发异常,但不会使用无效数据.从文档:
If nextInt()
fails, it throws an exception but doesn't consume the invalid data. From the documentation:
然后您再次递归调用meth()
,这将尝试第二次使用相同的无效数据,再次失败(不使用它),然后递归.
You're then recursively calling meth()
again, which will try to consume the same invalid data a second time, fail again (without consuming it), and recurse.
首先,我不会在这里首先使用递归.最好选择一个简单的循环.接下来,如果输入无效,则应在再次尝试之前适当地使用它.最后,考虑使用hasNextInt
而不是仅使用nextInt
并捕获异常.
Firstly, I wouldn't use recursion here in the first place. Prefer a simple loop. Next, if you have invalid input you should consume it appropriately before trying again. Finally, consider using hasNextInt
instead of just using nextInt
and catching the exception.
所以也许是这样的:
import java.util.Scanner;
class Test {
public static void main(String[] args){
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the number here:");
while (!scanner.hasNextInt() && scanner.hasNext()) {
System.out.println("Error");
// Skip the invalid token
scanner.next();
}
if (scanner.hasNext()) {
int value = scanner.nextInt();
System.out.println("You entered: " + value);
} else {
System.out.println("You bailed out");
}
}
}
}
这篇关于Scanner(System.in)-无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!