扫描仪异常重试 [英] Scanner Exception Retry
问题描述
如何在异常发生时重试扫描器?
考虑此应用程序在CLI模式下运行。
How to make scanner retry when exception occur?
Consider this app running on CLI mode.
示例:
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
输入,然后引发错误。但是我想要错误消息出现后。应该要求用户再次输入 width 。
If the user not inputting double
type input, then the error thrown. But i want after the error message appears. It's should be asking the user input the width again.
该怎么做?
推荐答案
如果我正确理解了您的要求,则希望该程序要求用户在输入失败后重新输入正确的输入。在这种情况下,您可以执行以下操作:
If I understood you correctly, you want the program to ask the user to re-enter a right input after it fails. In that case you can do something like:
boolean inputOk = false;
while (!inputOk) {
System.out.print("Define width: ");
try {
width = scanner.nextDouble();
inputOk = true;
} catch (InputMismatchException e) {
System.err.println("That's not a number!");
scanner.nextLine(); // This discards input up to the
// end of line
// Alternative for Java 1.6 and later
// scanner.reset();
}
}
注意:您只能 捕获并重试 InputMismatchException
。 nextXxx
方法抛出其他异常,如果您尝试重试这些异常,则应用程序将陷入无限循环。
Note: you should only catch and retry for a InputMismatchException
. The nextXxx
methods throw other exceptions, and if you attempt to retry those, your application will go into an infinite loop.
这篇关于扫描仪异常重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!