1

I am trying to accept only three numbers from my input: 1, 2, 3. Any other different than that must be invalid. I have created method but I don't have an idea why it did not working. What must I change?

int number;
do {
    System.out.println("Enter 1, 2 or 3");
    while (!scanner.hasNextInt()) {
        System.out.println("Invalid input!");
    }
    number = scanner.nextInt();
} while (number == 1 || number == 2 || number == 3)
return number;
IntoTheDeep
  • 3,337
  • 11
  • 34
  • 69

1 Answers1

2

Your loop logic

do {
    ...
} while (number == 1 || number == 2 || number == 3);

requires staying in the loop for as long as the answer is valid. You want to invert your condition:

do {
    ...
} while (!(number == 1 || number == 2 || number == 3));

or use De Morgan's Law to invert individual components:

do {
    ...
} while (number != 1 && number != 2 && number != 3);

In addition, when Scanner's hasNextInt returns false, you need to take the invalid input off the scanner, for example with nextLine that you ignore. Otherwise you get an infinite loop:

while (!scanner.hasNextInt()) {
    System.out.println("Invalid input!");
    scanner.nextLine(); // This input is ignored
}
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399