Reputation: 3771
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
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
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
players != 2
is true, so the whole expression is trueplayers != 1
is true, so the whole expression is trueYou want &&
, not ||
.
Upvotes: 3