java扫描程序异常重试
发生异常时如何使扫描仪重试
考虑这个应用程序在CLI模式下运行。
例如:
System.out.print("Define width: ");
try {
width = scanner.nextDouble();
} catch (Exception e) {
System.err.println("That's not a number!");
//width = scanner.nextDouble(); // Wrong code, this bring error.
}
如果用户没有输入double
类型的输入,则抛出错误。但我想在出现错误消息之后。它应该要求用户再次输入宽度
怎么做
# 1 楼答案
如果我理解正确,您希望程序在失败后要求用户重新输入正确的输入。在这种情况下,您可以执行以下操作:
注意:您应该只捕获并重试一次^{。
nextXxx
方法会抛出其他异常,如果您尝试重试这些异常,您的应用程序将进入无限循环# 2 楼答案
这个很好用,我仔细检查过了