Reputation: 1037
This code give me infinite loop although sum become equals to 7 and become equals to (point)
while ( sum!=point || sum!=7)
{
rollDices();
System.out.println("rolling dices .. sum="+sum);
} //end while
but if I do this:
while(sum!=point)
or this
while(sum!=7)
it works fine without any problem
Upvotes: 0
Views: 176
Reputation: 9038
What happens to you is the following
the condition sum != point || sum!=7
always returns true if point != 7.
so think point = 12 and you get on sum 6.
6 != 12 -> true
6 != 7 -> true
true || true -> true
lets imagine you get 7 on sum
7 != 12 -> true
7 != 7 -> false
true || false -> true
Upvotes: 1
Reputation: 62052
If you're stuck and can't figure out why your ||
or &&
isn't doing what you want it to do, work out a "truth table".
For ||
, the OR
operator:
true || false //returns true
true || true //returns true
false || true //returns true
false || false //returns false
And for &&
, the AND
operator:
true && true //returns true
true && false //returns false
false && true //returns false
false && false //returns false
Upvotes: 6
Reputation: 4799
Your logic is slightly flawed. Your statement is saying while sum is not equal to point or sum is not equal to 7. It will always be not equal to one of them, unless they are the same.
I think you wanted to use &&
:
while(sum!=point && sum!=7){
rollDices();
System.out.println("rolling dices .. sum="+sum);
}
With the &&
once sum is equal to 7 or point it will exit the loop.
Upvotes: 5
Reputation: 2562
I'm assuming you wanted && instead of ||. This makes it so that when sum becomes equal to 7 it will get out of the loop.
while( sum!=point && sum!=7){
rollDices();
System.out.println("rolling dices .. sum="+sum);
}//end while
So the only time it will stay in the loop is when sum isn't equal to point and sum isn't equal to 7.
Also a side note - Are you sure you want sum != 7? Or is sum < 7 what you want in case sum became larger than 7?
Upvotes: 1