使用用户输入在Java中尝试/捕获循环

时间:2015-02-13 01:13:36

标签: java exception-handling try-catch

我的代码应该从用户获取浮点值输入,一旦用户连续输入2个无效输入(非浮点数),程序就会停止并汇总有效输入并向用户吐出总和。这是代码: System.out.println(“请输入一组浮点值。”);

    Scanner keyboard = new Scanner(System.in);
    int tries = 0;
    int maxTries = 2;
    double sum = 0;

    while (tries < 2) { 
        try {
             while (keyboard.hasNext()){
                 sum += keyboard.nextDouble();
                 tries = 0; // reset counter because of valid input
             }
        }
        catch (InputMismatchException e) {
            System.out.println("Invalid input. Float values "
                    + "only please.");
            tries += 1; // tries +1 because invalid input
        }
    }
    System.out.printf("The sum of your inputs is: %d", sum);

我的例外是过早抛出,一旦我输入一个无效的输入程序停止并总结。我无法弄清楚如何允许用户连续两次无效(非浮点)输入,然后抛出异常。感谢。

3 个答案:

答案 0 :(得分:2)

try{
        Scanner keyboard = new Scanner(System.in);
        int tries = 0;
        int maxTries = 2;
        double sum = 0;

        while (tries < 2) { 
            try {
                 while (keyboard.hasNext()){
                     double d = keyboard.nextDouble();
                     sum += d;
                     tries = 0; // reset counter because of valid input
                 }
            }
            catch (InputMismatchException e) {
                System.out.println("Invalid input. Float values "
                        + "only please.");
                tries += 1; // tries +1 because invalid input
                keyboard.nextLine();
            }
        }
        System.out.printf("The sum of your inputs is: %f", sum);
    }catch(Exception e){
        e.printStackTrace();
    }

由于键盘扫描程序中仍有输入,因此会抛出两次异常,并尝试继续读取。通过阅读下一行来“冲洗”它。

此外,在输出上,使用%f

打印

答案 1 :(得分:1)

扫描程序为您提供hasNexthasNextXXX,其中XXX是您想要的类型,以避免抛出异常。

无论如何,如果用户提供无效输入,它将保持在流中,直到您使用它为止。您可以使用next()或(有时更好)使用nextLine()方法轻松完成此操作。因此 避免将异常用作流控制逻辑的主要部分

因此,请更改您的代码,而不是允许任何类型数据的hasNext,请使用hasNextDouble()
BTW要打印您需要使用%f的浮点数,%d用于整数。

Scanner keyboard = new Scanner(System.in);
int tries = 0;
int maxTries = 2;
double sum = 0;

while (tries < maxTries) {
    if (keyboard.hasNextDouble()) {
        sum += keyboard.nextDouble();
        tries = 0; // reset counter because of valid input
    } else {
        System.out.println("Invalid input. Float values "
                + "only please.");
        keyboard.next();// consume one invalid token from user input
        tries += 1; // tries +1 because invalid input
    }
}
System.out.printf("The sum of your inputs is: %f", sum);

示例:

输入:1 2 3 b 4 foo bar
输出:

1 2 a 3 a 4 aa a
Invalid input. Float values only please.
Invalid input. Float values only please.
Invalid input. Float values only please.
The sum of your inputs is: 10,000000

答案 2 :(得分:0)

处理此问题的更简单方法是将每个输入行作为字符串(keyboard.nextLine)读取。然后尝试将Double.parseDouble转换为double,捕获任何NumberFormatException以检查尝试次数等。