Java Scanner异常处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24414299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Scanner exception handling
提问by Airwavezx
I would like to receive a Double from the user and handle the exception thrown in case the user didn't input a double/int; in that case I'd like to ask the user to insert the amount again. My code gets stuck in a loop if the exception is caught, and keeps printing "Insert amount".
我想从用户那里接收一个 Double 并处理在用户没有输入 double/int 的情况下抛出的异常;在这种情况下,我想请用户再次插入金额。如果异常被捕获,我的代码就会陷入循环,并继续打印“插入数量”。
private static double inputAmount() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Insert amount:");
try {
double amount = input.nextDouble();
return amount;
}catch (java.util.InputMismatchException e) {continue;}
}
}
Thank you in advance.
先感谢您。
采纳答案by awksp
Your program enters an infinite loop when an invalid input is encountered because nextDouble()
does notconsume invalid tokens. So whatever token that caused the exception will stay there and keep causing an exception to be thrown the next time you try to read a double.
你的程序进入时遇到一个无效的输入,因为一个无限循环,nextDouble()
并没有消耗无效令牌。因此,导致异常的任何标记都将保留在那里,并在您下次尝试读取 double 时继续引发异常。
This can be solved by putting a nextLine()
or next()
call inside the catch
block to consume whatever input was causing the exception to be thrown, clearing the input stream and allowing the user to input something again.
这可以通过在块内放置一个nextLine()
或next()
调用来解决这个问题,catch
以消耗导致抛出异常的任何输入,清除输入流并允许用户再次输入某些内容。
回答by Fradenger
The reason is that it keeps reading the same value over and over, so ending in your catch clause every time.
原因是它一遍又一遍地读取相同的值,因此每次都以 catch 子句结尾。
You can try this:
你可以试试这个:
private static double inputAmount() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Insert amount:");
try {
return input.nextDouble();
}
catch (java.util.InputMismatchException e) {
input.nextLine();
}
}
}
回答by Vivin
Its because after the exception is caught, its stays in the buffer of scanner object. Hence its keeps on throwing the exception but since you handle it using continue, it will run in a loop. Try debugging the program for a better view.
这是因为异常被捕获后,它会留在扫描仪对象的缓冲区中。因此它不断抛出异常,但由于您使用 continue 处理它,它将在循环中运行。尝试调试程序以获得更好的视图。
回答by Kuldeep Verma
This method keeps on executing the same input token until it finds a line separator i.e. input.nextLine()
or input.next()
此方法继续执行相同的输入标记,直到找到行分隔符,即input.nextLine()
或input.next()
Check out the following code
查看以下代码
private static double inputAmount()
{
Scanner input = new Scanner(System.in);
while (true)
{
System.out.println("Insert amount:");
try
{
double amount = input.nextDouble();
return amount;
}
catch (java.util.InputMismatchException e)
{
input.nextLine();
}
}
}