简体   繁体   English

做while无限循环

[英]Do while infinite loop

I am trying to write a method that asks a user for a positive integer.我正在尝试编写一个方法,要求用户输入一个正整数。 If a positive integer is not inputted, a message will be outputted saying "Please enter a positive value".如果未输入正整数,则会输出“请输入正值”的消息。 This part is not the issue.这部分不是问题。 The issue is that when I try to implement a try catch statement that catches InputMismatchExceptions (in case user inputs a character or string by accident), the loop runs infinitely and spits out the error message associated with the InputMistmatchException.问题是,当我尝试实现捕获 InputMismatchExceptions 的 try catch 语句(以防用户意外输入字符或字符串)时,循环无限运行并吐出与 InputMistmatchException 关联的错误消息。

Here is my code:这是我的代码:

private static int nonNegativeInt(){
        boolean properValue = false;
        int variable = 0;
        do {
            try {
                while (true) {
                    variable = scanner.nextInt();
                    if (variable < 0) {
                        System.out.println("Please enter a positive value");
                    } else if (variable >= 0) {
                        break;
                    }
                }
                properValue = true;
            } catch (InputMismatchException e){
                System.out.println("That is not a valid value.");
            }
        } while (properValue == false);
        return variable;
    } 

Essentially what is happening is that the scanner runs into an error when the given token isn't valid so it can't advance past that value.本质上,当给定的令牌无效时,扫描器会遇到错误,因此它无法超过该值。 When the next iteration starts back up again, scanner.nextInt() tries again to scan the next input value which is still the invalid one, since it never got past there.当下一次迭代再次开始时,scanner.nextInt() 再次尝试扫描下一个仍然是无效的输入值,因为它从未通过那里。

What you want to do is add the line你想要做的是添加行

scanner.next(); 

in your catch clause to basically say skip over that token.在您的 catch 子句中,基本上说跳过该标记。

Side note: Your method in general is unnecessarily long.旁注:您的方法通常不必要地长。 You can shorten it into this.你可以把它缩短成这个。

private static int nonNegativeInt() {
    int value = 0;
    while (true) {
        try {
            if ((value = scanner.nextInt()) >= 0)
                return value;
            System.out.println("Please enter a positive number");
        } catch (InputMismatchException e) {
            System.out.println("That is not a valid value");
            scanner.next();
        }
    }
}

you are catching the exception but you are not changing the value of variable proper value so the catch statement runs forever.您正在捕获异常,但您没有更改变量正确值的值,因此 catch 语句将永远运行。 Adding properValue = true;添加properValue = true; or even a break statement inside the catch statement gives you the required functionality!甚至 catch 语句中的break语句为您提供所需的功能!

I hope I helped!我希望我有所帮助!

Just add a break statement inside your catch.只需在您的 catch 中添加一个break语句。
Btw, you can get rid of the while loop by rewriting it like this:顺便说一句,您可以通过像这样重写它来摆脱while循环:

try {
    variable = scanner.nextInt();
    if (variable < 0) {
        System.out.println("Please enter a positive value");
    } else {
        properValue = true;
    }
}
//... 

You can declare the scanner at the start of the do-while-loop, so nextInt() will not throw an exception over and over.您可以在 do-while 循环开始时声明扫描器,因此 nextInt() 不会一遍又一遍地抛出异常。

private static int nonNegativeInt(){
    boolean properValue = false;
    int variable = 0;
    do {
        scanner = new Scanner(System.in);
        try {
            while (true) {
                variable = scanner.nextInt();
                if (variable < 0) {
                    System.out.println("Please enter a positive value");
                } else if (variable >= 0) {
                    break;
                }
            }
            properValue = true;
        } catch (InputMismatchException e){
            System.out.println("That is not a valid value.");
        }
    } while (properValue == false);
    return variable;
} 

This is indeed nearly identical to SO: Java Scanner exception handling这确实与SO: Java Scanner exception processing 几乎相同

Two issues:两个问题:

  • You need a scanner.next();你需要一个scanner.next(); in your exception handler在您的异常处理程序中

    ... AND ... ... 和 ...

  • You don't really need two loops.你真的不需要两个循环。 One loop will do just fine:一个循环就可以了:

     private static int nonNegativeInt(){ boolean properValue = false; int variable = 0; do { try { variable = scanner.nextInt(); if (variable < 0) { System.out.println("Please enter a positive value"); continue; } else if (variable >= 0) { properValue = true; } } catch (InputMismatchException e){ System.out.println("That is not a valid value."); scanner.next(); } } while (properValue == false); return variable; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM