【发布时间】:2016-05-20 20:27:27
【问题描述】:
我准备了以下代码:
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"
以此类推……
它没有给我再次选择的机会。有人可以解释一下我在做什么错吗? 谢谢
【问题讨论】:
-
如果
inChoice抛出异常,这意味着扫描仪没有消耗该值,因此每次您尝试执行nextInt时它都会尝试解析相同的错误值。通过在catch部分添加next()来使用它。还要避免 try-catch 并简单地将 if-else 与hasNextInt()条件一起使用。 -
使用
intChoice = Integer.parseInt(inChoice.nextLine())。并使您的变量名称不同,以便int和Scanner不会相差 1 个字符! -
@Pshemo 如何在
hasNextInt()之后从扫描仪中检索我的值。我的意思是它返回布尔值。假设我检查了我的扫描仪是否有有效的整数编号。之后如何找回我的号码? -
hasNextInt()只是检查提供的值是否为整数。因此,如果它返回true,只需使用nextInt(),您应该得到int的值。如果它返回false,那么输入要么不是数字系列,要么它的值超出int范围。在这种情况下,您可以使用next()来使用此类令牌并要求用户提供新令牌。
标签: java while-loop exception-handling