1

I am programming a monopoly type game on java and am having a little trouble setting up the validation for the player select function. The user will have to chose between 2-4 players.

Below is my attempt at doing this utilizing an if else statement and a while loop.

I can't figure out the right way of implementing this and would appreciate any advice.

int numberPlayers = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter Number of players (2-4)");

if (scanner.nextInt() >= 2 && scanner.nextInt() <= 4) {
    numberPlayers = scanner.nextInt();
    System.out.println(numberPlayers + " players selected");
} else {
    while (scanner.nextInt() < 2 || scanner.nextInt() > 4) {
        System.out.println("Not a valid choice. Please enter Number of players (2-4)");
    }
}
MTCoster
  • 5,868
  • 3
  • 28
  • 49
  • 2
    I see your code making three calls to the scanner to retrieve an integer input, when you probably should only be making one call. – Tim Biegeleisen Feb 09 '19 at 15:55
  • 5
    Yikes, you are throwing out the user's input with that while loop condition as this: `while (scanner.nextInt() < 2 || scanner.nextInt() > 4)` gets the user's input and completely discards it since the input is not put into a variable. Get the user's input into a variable *within* the while loop, not the while loop's condition. Check the state of this variable within the condition. – Hovercraft Full Of Eels Feb 09 '19 at 15:55
  • Every time you say scanner.nextInt() your program looks for a user input instead call it once and store it in a variable. – Sanath Kumar Feb 09 '19 at 16:21

1 Answers1

0

You can use a do-while loop to ask the user at least once for the player count and keep asking until the input is valid.

public int askForPlayers(Scanner scanner) {
    int numberPlayers = 0;
    do {
        System.out.println("Please enter Number of players (2-4)");
        numberPlayers = scanner.nextInt();
    } while(numberPlayers < 2 || numberPlayers > 4);
    return numberPlayers;
}

When you use a Scanner object, keep in mind that the user might enter something else that is not a number. You have to work with hasNextInt() and next() to deal with such a situation. Also, when you close the Scanner object, you are also closing the InputStream you used, see Close a Scanner linked to System.in.

Progman
  • 16,827
  • 6
  • 33
  • 48