开发者

Source of Infinite Loop

开发者 https://www.devze.com 2023-04-10 03:52 出处:网络
Everytime I run this code, the console goes into an infinite loop printing \"Please input a number\". I do not understand why this is happening. Thanks in advance.

Everytime I run this code, the console goes into an infinite loop printing "Please input a number". I do not understand why this is happening. Thanks in advance.

  开发者_如何学Go  boolean check = true;
    int temp = 0;
    while(check==true){
        try{

            temp= asker.nextInt();
            check = false;
        }
        catch(InputMismatchException e){
            System.out.println("Please input a number.");
        }
    }

Edit: asker is a Scanner. The purpose of the code is to loop until an integer is inputted by the user.


The method asker.NextInt() is throwing an InputMismatchException, indicating that the input received from asker (assuming it's a Scanner) isn't actually an integer. This exception causes the loop to restart without setting check to false.

Print the exception within the catch block to get more information about the failure. But most likely, you're feeding your application something (lots and lots of something, if it's looping like that) that doesn't actually contain integer values.


You never want to actually "Use" try/catch--by that I mean don't use it as part of your program logic--this is what you are doing.

One big problem is that, like your app, you don't see the stack trace. Eating a stack trace in an exception is almost always wrong.

If you do have to catch an exception, handle it near the catch as well as you can, but it's better to set up your code so that the exception can't be thrown anyway.

Discard this advice if your teacher told you to do it this way, but remember in the back of your mind that it's poor form.

Also don't tell your teacher that it's poor form :) he either doesn't know in which case he won't understand why or he does know and is using this to show you how try/catch works.


What is asker, a Scanner? If nextInt() fails, it doesn't consume any input, so when you catch your exception and loop back around to try again, it ends up just reading the same bad input again.

You should do something in the catch block to consume the invalid input, so that the next time around, it can read some different input. Call asker.nextLine() maybe, and ignore the return value.


You need to break the loop and report why the loop occurs

boolean NotValid = true;
int temp = 0;
while(NotValid){
    try{

        temp= asker.nextInt();
        NotValid = false;
        break; // stop
    }
    catch(InputMismatchException e){
        System.out.println("Please input a number. reason why:");
        System.out.println(e);
        NotValid = true;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消