[英]While loop with try-catch blocks doesn't wait for input in the try block after looping once
[英]Why doesn't scanner ask for an other input in a try-catch while loop java
假设我需要继续询问用户,直到他输入double
。
我做的是我使用了一个while循环并检查是否有异常。
如果有异常,我会去询问下一个输入。
double bal = 0;
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.println("Enter the balance");
bal = sc.nextDouble();
break;
} catch (Exception e) {
System.out.println("That isn't a number");
}
}
System.out.println("Bal is " + bal);
sc.close();
但是如果我输入一个非double,那么它不会要求下一个输入,继续打印以无限循环结束的那两行。
Enter the balance
XYZ
That isn't a number
Enter the balance
That isn't a number
Enter the balance
That isn't a number
Enter the balance
That isn't a number
....
我错过了什么?
您需要通过在catch块中调用sc.next()
来丢弃流中的先前输入。 遗憾的是,当输入失败时,扫描仪不会自动执行此操作。
使用sc.next()
来丢弃错误的输入:
while (true) {
try {
System.out.println("Enter the balance");
bal = sc.nextDouble();
break;
} catch (InputMismatchException e) {
System.out.println("That isn't a number");
sc.next();
}
}
另外我建议捕获特定的异常(在本例中为InputMismatchException
)。 这样,如果出现其他问题(例如,标准输入流已关闭),您将不会错误地打印"That isn't a number"
。
来自nextDouble
文档:
如果翻译成功,扫描仪将超过匹配的输入。
因此,当输入不匹配时,扫描仪不会超过它。 因此,当你执行nextDouble
时,下一次迭代输入尚未被清除,它仍然会读取相同的输入。
您应该通过在失败时读取next()
来提前输入,或者将输入作为字符串读取并尝试解析结果,即使值非法,输入已被清除,下一次迭代也可以读取新值/输入:
public static void main(String[] args) {
double bal = 0;
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.println("Enter the balance");
bal = Double.parseDouble(sc.next());
break;
} catch (Exception e) {
System.out.println("That isn't a number");
}
}
System.out.println("Bal is " + bal);
sc.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.