java.util.Scanner:为什么我的 nextDouble() 没有提示?
import java.util.*;
public class June16{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
double b=0;
boolean checkInput = true;
do{
try{
System.out.println("Input b : ");
b = kb.nextDouble();
checkInput = false;
}catch(InputMismatchException ime){
}
}while(checkInput);
}
}
抛出InputMismatchException后,为什么我的程序不提示输入? :D
import java.util.*;
public class June16{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
double b=0;
boolean checkInput = true;
do{
try{
System.out.println("Input b : ");
b = kb.nextDouble();
checkInput = false;
}catch(InputMismatchException ime){
}
}while(checkInput);
}
}
After InputMismatchException is thrown, why my program not prompt for input? :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自文档:
这就是为什么如果您不输入有效的双精度数,您最终会陷入无限循环。处理异常时,使用
kb.next()
移至下一个标记。From the documentation:
This is why you end up in an infinite loop if you don't enter a valid double. When you handle the exception, move to the next token with
kb.next()
.因为如果 Scanner.nextDouble() 失败,它会将令牌留在队列中(然后一次又一次地读取令牌,导致它一次又一次地失败)。
请尝试以下操作:
}
说明工作示例的 ideone.com 演示
Because if the
Scanner.nextDouble()
failes it leaves the token on the queue, (which is then read again and again causing it to fail over and over again).Try the following:
}
ideone.com demo illustrating working example
这是因为 nextDouble 将采用您输入的十进制数字,但您输入的回车符仍然未被扫描仪读取。下次循环时它会读取输入,但是等等!那里有一个回车符,所以...不需要扫描任何东西。它只是处理回车符。当然,程序发现它不是双精度数,所以你会得到一个异常。
你如何解决它?好吧,有一些东西可以扫描 nextDouble (即 next())留下的任何剩余内容,然后再次扫描下一个 double。
This is due to the fact that nextDouble will take the decimal number you entered, but there is still a carriage return that you enter that was not read by the scanner. The next time it loops it reads the input, but wait! there is a carriage return there, so... no need to scan anything. It just processes the carriage return. Of course, the program finds that it is not a double, so you get an exception.
How do you fix it? Well, have something that scans whatever leftovers were left by the nextDouble (namely a next()) and then scan the next double again.