0

I am trying to give the user the option to input the number of players again if the user inputs the wrong type of data. The code below gives me an infinite loop, please help me find the way to correct it.

boolean isValid = false;
    int playerId = 1;
    int numberOfPlayers = -1;

    while(isValid != true) {

        try {
            System.out.print("How many players? (1-6) ");
            numberOfPlayers = s.nextInt();
            while(numberOfPlayers > 6 || numberOfPlayers <= 0){
                System.out.print("Must be between 1 and 6 players. Please try again: ");
                numberOfPlayers = s.nextInt();
            }
            isValid = true;
        }

        catch (Exception e) {

            System.out.println("That is not a number!! >:( Please try again");
            isValid = false;

        }

    }
  • tl;dr: `nextInt()` doesn't move to the next line of input, so it's just reading your first number over and over. – azurefrog May 23 '21 at 17:41
  • Not quite that. After you catch an exception, use `s.next()` to move past the invalid input. – khelwood May 23 '21 at 17:46

0 Answers0