[英]java.lang.StackOverflowError on recursive function call
我写了一个程序,它接受来自用户的数字,如果用户输入,例如,一个字符串而不是一个数字,那么我递归调用 function 让用户输入一个数字,但在我的例子中,程序抛出一个StackOverflowException 错误。 如果你知道问题是什么,请写。
代码:
private static void inputMethod() {
try {
System.err.print("Enter a range from ");
c = input.nextInt();
System.err.print("Enter a range to ");
d = input.nextInt();
if(c > d) {
System.err.println("Invalid Range Entry");
inputMethod();
return;
}
System.err.print("Enter the sum of digits ");
q = input.nextInt();
findNaturalNumbers();
} catch(InputMismatchException e) {
inputMethod();
}
}
问题是当InputMismatchExcpetion
被抛出时,导致错误的垃圾输入仍在等待下一次扫描仪调用再次读取。 这样您就可能会返回 go 并尝试使用next()
或nextLine()
再次读取它。
解决方法是“冲厕所”,可以这么说,通过在InputMismatchException
处理程序中调用next()
或nextLine()
:
boolean inputWasGood = false;
while (!inputWasGood){
try {
System.out.println("Enter a number: ");
c = input.nextInt();
inputWasGood = true;
} catch (InputMismatchException ex) {
input.nextLine(); // FLUSH AWAY THE GARBAGE!!
System.out.println("Please don't enter garbage!");
}
}
// FINALLY! We got some good input...
如果输入字母而不是数字,则input.nextInt()
方法会引发异常,但输入 stream 中的 cursor position 仍然没有指向扫描仪。 在异常处理程序中,您再次调用inputMethod()
,并且由于 cursor position 相同,因此input.nextInt()
将再次抛出异常,这将导致再次调用inputMethod()
等等,直到堆栈被炸毁。 您应该做的是使用hasNextInt()
方法检查 stream 上的下一个标记是否是格式正确的 integer ,如果是,请使用nextInt()
读取它。 为了简化这个过程,你可以尝试创建一个额外的方法,它会提示用户并要求输入,直到提供正确的输入:
private int readInt(Scanner scanner, String prompt) {
while (true) {
System.out.println(prompt);
if (scanner.hasNextInt()) {
return scanner.nextInt();
}
System.out.println("Incorrect format of an integer number");
scanner.nextLine();
}
}
然后你可以像这样使用它:
do {
c = readInt(input, "Enter a range from ");
d = readInt(input, "Enter a range to ");
if(c > d) {
System.err.println("Invalid Range Entry");
}
} while (c > d);
q = readInt(input, "Enter the sum of digits ");
findNaturalNumbers();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.