如何在发生异常时重新扫描扫描仪? 考虑在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
类型输入,则抛出错误。但我想在出现错误信息后。应该要求用户再次输入 width 。
怎么做?
答案 0 :(得分:3)
如果我理解正确,您希望程序在失败后要求用户重新输入正确的输入。在这种情况下,您可以执行以下操作:
boolean inputOk = false;
while(!inputOk)
{
System.out.print("Define width: ");
try {
width = scanner.nextDouble();
inputOk = true;
} catch (Exception e) {
System.err.println("That's not a number!");
scanner.next(); // here is to re-enter it.
}
}
答案 1 :(得分:1)
这完美无缺,我已经仔细检查了
Scanner in;
double width;
boolean inputOk = false;
do
{
in=new Scanner(System.in);
System.out.print("Define width: ");
try {
width = in.nextDouble();
System.out.println("Greetings, That's a number!");
inputOk = true;
} catch (Exception e) {
System.out.println("That's not a number!");
in.reset();
}
}
while(!inputOk);
}
答案 2 :(得分:0)
您可以使用:
System.out.print("Define width: ");
boolean widthEntered = false;
// Repeath loop until width is entered properly
while (!widthEntered) {
try {
// Read width
width = scanner.nextDouble();
// If there is no exception until here, width is entered properly
widthEntered = true;
} catch (Exception e) {
System.err.println("That's not a number!");
}
}