gpt4 book ai didi

java - 捕获异常时不定式递归

转载 作者:行者123 更新时间:2023-12-04 20:38:39 24 4
gpt4 key购买 nike

这是我输入学号的代码:当用户以意想不到的格式输入数字时,我会要求他们通过递归重新输入。但它以不定式递归结束。为什么?

private static int inputStudentNumber(){
System.out.println("Enter the student number:");
int studentNum;
try {
//Scanner in initialized before calling this method
studentNum = in.nextInt();
return studentNum;
} catch(Exception e) {
System.out.println("Invalid input, it can only be integer.");
return inputStudentNumber();
}
}

最佳答案

仔细看看 javadocs for Scanner.nextInt :

This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched. (emphasis added)

如果不成功,则扫描仪不先进。这意味着如果您尝试再次调用 nextInt(),您将尝试从与以前相同的 token 获取一个 int,并且您将再次获得一个 InputMismatchException

您的代码基本上是这样说的:尝试将下一个标记读取为 int。如果失败,递归尝试再次将 token 读取为 int。如果失败,递归尝试再次将 token 读取为 int。如果失败...(依此类推,直到您从太多递归中得到 StackOverflowException)。

如果你想为此使用递归,你可能应该使用 next() 跳到下一个标记。并且只捕获 InputMismatchException,这样您就不会同时捕获 NoSuchElementException(System.in 不会发生这种情况,但这是一个很好的做法一般来说——如果您稍后决定从一个文件中读取,而该文件已经到达结尾怎么办?)。

} catch(InputMismatchException e) {
System.out.println("Invalid input, it can only be integer.");
in.next(); // skip this token
return inputStudentNumber();
}

更好的方法是首先避免使用异常来控制您的逻辑。为此,您必须提前知道 nextInt 是否会成功。幸运的是,hasNextInt()让你做到这一点!

private static int inputStudentNumber() {
System.out.println("Enter the student number:");
if (in.hasNextInt()) {
return in.nextInt();
} else {
System.out.println("Invalid input, it can only be integer.");
in.next(); // consume the token
return inputStudentNumber();
}
}

这里的优势——除了一般的“不要对控制流使用异常”建议之外——是基本情况非​​常清楚。如果有一个 int 准备好了,那就是你的基本情况;如果不是,则必须推进扫描仪并重试。

关于java - 捕获异常时不定式递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28181347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com