我编写了以下代码:
public static void main(String[] args) {
Scanner inChoice = new Scanner(System.in);
while(true)
{
try
{
System.out.println("--------------------------------------------------------");
System.out.println("Make your choice :");
System.out.println("For integer - CHOOSE 1");
System.out.println("For floating-point numbers - CHOOSE 2");
intChoice = inChoice.nextInt();
break;
}
catch (InputMismatchException imex)
{
System.out.println("You have made a wrong selection. Try again");
continue;
}
}
}
问题是,当我选择其他的东西,然后是整数(例如“w”)。我的意图是在例外之后再给一个选择的机会。但是,相反,我的代码会无限地捕获块和循环,并给我消息:
"--------------------------------------------------------"
"Make your choice :"
"For integer - CHOOSE 1"
"For floating-point numbers - CHOOSE 2"
"You have made a wrong selection. Try again"
"--------------------------------------------------------"
"Make your choice :"
"For integer - CHOOSE 1"
"For floating-point numbers - CHOOSE 2"
"You have made a wrong selection. Try again"
"--------------------------------------------------------"
"Make your choice :"
"For integer - CHOOSE 1"
"For floating-point numbers - CHOOSE 2"
"You have made a wrong selection. Try again"
结局如此..。
这不会让我有选择的机会。有人能解释一下我做错了什么吗?谢谢
发布于 2016-05-20 12:26:33
发生异常时,不会使用输入。它就留在那里。您需要使用它,否则它会一直抛出异常。
只需在异常块中添加这一行(当然是在continue
之前):
inChoice.next();
https://stackoverflow.com/questions/37346629
复制相似问题