How do I stop while loop from running infinitely?

Neill B :

Can't figure out how to stop this while loop from repeating infinitely. I'm using hasNextInt to check if user input is an int. If an int is not entered the loop repeats infinitely.

public static void validatingInput(){
    Scanner scan = new Scanner(System.in);

    boolean valid = false;
    int userNumber = 0;

    while(!valid) { 
    System.out.println("Enter number between 1 and 20: ");

    if (scan.hasNextInt()) {    
    userNumber = scan.nextInt();
    valid = true;   
    } else 
        System.out.print("Not an int. ");
    }

}
Mureinik :

You need to consume a token from a scanner in order to allow it to read the next token:

while (!valid) { 
    System.out.println("Enter number between 1 and 20: ");

    if (scan.hasNextInt()) {    
        userNumber = scan.nextInt();
        valid = true;   
    } else 
        System.out.print("Not an int. ");
        scan.next(); // Skip a token
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117460&siteId=1