2

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. ");
    }

}

2 Answers 2

4

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can break any loops with break;. Check the state of an input and break the while when you want

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.