LLL
LLL

Reputation: 3771

Scanner in a while loop, loop won't quit

I want to get input from the user which is either 1 or 2 and propmpt the user for the answer again if he doesn't comply with the right answer.

I tried doing it with a while loop:

    int players = 0;
    players = sc.nextInt();

    while (players != 1 || players != 2)
    {
        System.out.println("Wrong input, choose again:");
        players = sc.nextInt();
        System.out.println(players);
    }

and a do-while:

    do
    {
        players = sc.nextInt();
    }
    while (players != 1 || players!= 2);

But the loop never quits, even when I input the right number.

And this logic used to work with scanf in C.

Upvotes: 0

Views: 194

Answers (2)

Dici
Dici

Reputation: 25950

players != 1 || players!= 2 is always true and should be players != 1 && players!= 2. I seriously doubt this wrong logic worked with C !

If you know a little about boolean algebra, you must know that not(not(A) or not(B)) <=> A and B. In your case, it means that the negation of your condition (which must be true for the loop to exit) is players == 1 && players == 2, which is trivially impossible.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691685

players != 1 || players != 2

this condition is always true. || means or. So the expression is true if at least one of its two operands is true

  • if players is 1, then players != 2 is true, so the whole expression is true
  • if players is 2, then players != 1 is true, so the whole expression is true
  • if players is anything else, then both expressions are true.

You want &&, not ||.

Upvotes: 3

Related Questions