【问题标题】:How to keep looping with try and catch to get correct input?如何通过 try 和 catch 保持循环以获得正确的输入?
【发布时间】:2018-05-30 20:12:08
【问题描述】:

我正在尝试创建一个检查整数的函数,并将继续循环,直到用户正确输入 17 或更高的整数。但是,如果我输入了错误的输入,例如“K”或“&”,它将陷入无限循环。

public static int getAge(Scanner scanner) {
    int age;
    boolean repeat = true;

    while (repeat) {
        try
        {
          System.out.println("Enter the soldier's age: ");
          age = scanner.nextInt();
          repeat = false;
        }
        catch(InputMismatchException exception)
        {
          System.out.println("ERROR: You must enter an age of 17 or higher");
          repeat = true;
        }
    }
    return age;
}

【问题讨论】:

标签: java input while-loop integer try-catch


【解决方案1】:

如果下一个可用的输入标记不是整数,nextInt() 将保留该输入未使用,缓冲在 Scanner 内。这个想法是您可能想尝试使用其他一些Scanner 方法来阅读它,例如nextDouble()。不幸的是,这也意味着除非您采取措施清除缓冲的垃圾,否则您对nextInt() 的下一次调用将只是尝试(并且失败)再次读取相同的垃圾。

因此,要清除垃圾邮件,您需要先调用next()nextLine(),然后再尝试再次调用nextInt()。这样可以确保下次您调用 nextInt() 时,它将有新数据可以处理,而不是相同的旧垃圾:

try {
    //...
} 
catch(InputMismatchException exception)
{
    System.out.println("ERROR: You must enter an age of 17 or higher");
    scanner.next();   // or scanner.nextLine()
    repeat = true;
}

【讨论】:

  • 好的,谢谢!我还在习惯扫描仪的工作方式。
【解决方案2】:

我不会将扫描仪传递给您的方法,我会尝试对其进行重构,并将该方法分配给您的 main 中的变量,如下所示:

我还在我的catch中使用递归来调用捕获异常时的方法,我还建议使用一般异常,使其捕获(异常异常)

  main method call of method
    ---------------------------
        int something= getAge();
        ----------------------------------------------------------

         method structure like this,
    ---------------------------------------------

        public static int getAge() {
            int age;
    age = scanner.nextInt();
            boolean repeat = true;

            while (repeat) {
                try
                {
                  System.out.println("Enter the soldier's age: ");
                  
                   
        if(age<=17){
                  repeat = false;
        }

    if(age>17){


    getAge();
    }
                }
                catch(InputMismatchException exception)
                {
                  System.out.println("ERROR: You must enter an age of 17 or higher");
                  getAge();
                }

            }
            return age;
        }
<!-- end snippet -->

【讨论】:

  • 各位有什么想法或想法吗?我也是java初学者,你觉得我的解决方案怎么样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
  • 2021-02-01
相关资源
最近更新 更多