Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source of Infinite Loop

Tags:

java

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.

    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.

like image 398
rmp2150 Avatar asked May 22 '26 23:05

rmp2150


1 Answers

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.

like image 71
Michael Petrotta Avatar answered May 24 '26 12:05

Michael Petrotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!