【问题标题】:Infinite while loop in java on exception [duplicate]java中的无限while循环异常[重复]
【发布时间】: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())。并使您的变量名称不同,以便 intScanner 不会相差 1 个字符!
  • @Pshemo 如何在hasNextInt() 之后从扫描仪中检索我的值。我的意思是它返回布尔值。假设我检查了我的扫描仪是否有有效的整数编号。之后如何找回我的号码?
  • hasNextInt() 只是检查提供的值是否为整数。因此,如果它返回true,只需使用nextInt(),您应该得到int 的值。如果它返回false,那么输入要么不是数字系列,要么它的值超出int 范围。在这种情况下,您可以使用next() 来使用此类令牌并要求用户提供新令牌。

标签: java while-loop exception-handling


【解决方案1】:

发生异常时,不消耗输入。它留在那里。你需要消耗它,否则它会一直抛出异常。

你只需要在异常块中添加这一行(当然在continue之前):

inChoice.next();

【讨论】:

  • inChoice.next(); 期望我按任意键。我想用相同的功能“跳过”这一步。我该怎么做?
  • "inChoice.next(); 期望我按任意键" 不。 inChoice.next(); 期望您按任意键和/或按回车键。
猜你喜欢
  • 2015-11-01
  • 2014-03-29
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多