【问题标题】:Do-while in try catch [closed]在尝试捕获时执行[关闭]
【发布时间】:2018-06-23 09:16:31
【问题描述】:

我在 catch 中得到无限循环...它应该要求用户再次输入。 请帮忙

public class Example {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int num = 0;
        do {
            try {
                System.out.print("Enter number : ");
                num = input.nextInt();
            } catch (Exception e) {
                System.out.println("Enter number only !!!");
            }
        } while (num != 5);
    }

}

【问题讨论】:

  • 这么有名气的用户怎么会这么不小心问问题。
  • @FarhanQasim 并且不知道如何删除自己的问题。

标签: java loops java.util.scanner do-while


【解决方案1】:

发生这种情况是因为您将非数字与 while(num!=5) 中的数字进行比较。由于异常,不会从用户那里获取另一个输入,并且先前的非数字输入被保存到“num”变量中,因此无限次发生异常并执行 catch(){}。

【讨论】:

    【解决方案2】:

    要退出 do-while 循环,您需要输入数字 5

    【讨论】:

    • 如果申请失败,我想允许用户再次输入号码
    • 对不起,一开始没有看到这个。你需要在 catch 子句中调用input.next();
    【解决方案3】:

    我没有明白你想要做什么。你做的事情应该是什么意思?无论如何,如果你想检查用户输入的数字是否是 NUMERIC 而不是 Non-Numeric,你应该这样做

    System.out.print("Enter Number ");  
    Scanner input = new Scanner(System. in);  
    
    try {   
    String str = input.next();  
    int x=  Integer.parseInt(str);         
    
    }  
    catch(Exception e) {  
     System.out.print("Type a Number, Not String");               
    }
    

    【讨论】:

    【解决方案4】:

    基本上,当您为a 之类的非数字输入执行num = input.nextInt(); 时,扫描仪a 中的缓冲区仍然存在,因为它未被读取,并且可用于您正在调用的下一次扫描与do-while。所以,你的无限循环开始了。

    通过在你的 catch 中使用 input.nextLine 清除输入缓冲区来解决它。

    catch (Exception e) {
        System.out.println("Enter number only !!!");
        input.nextLine();
    }
    

    查看@Ojasvi 的参考

    【讨论】:

      【解决方案5】:

      你没有增加 num 所以它将永远保持 0 并且会有无限循环

      【讨论】:

        【解决方案6】:

        试试这个:

        因为您错过了将 num = input.nextInt(); 放入您的 catch 块。 在您将输入数字设为 5 之前,它会一直保留在循环中。

        public class Example {
        
            public static void main(String[] args) {
        
                Scanner input = new Scanner(System.in);
                int num = 0;
                do {
                    try {
                        System.out.print("Enter number : ");
                        num = input.nextInt();
                    } catch (Exception e) {
                        System.out.println("Enter number only !!!");
                        num = input.nextInt();
                    }
                } while (num != 5);
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-12
          • 1970-01-01
          • 2012-09-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多