Home > database >  Condition for while loop doesn't work in java
Condition for while loop doesn't work in java

Time:10-29

I want the loop to repeat if the number is not equal to 0 and rest%2 is equal to 1 or -1. But this does not seem to work:

while (number != 0 && rest%2 == 1 || rest%2 == -1)

How do I have to write the code so it works?

CodePudding user response:

While it's good to learn about operator precedence, your expression can be reduced:

while (number != 0 && rest%2 != 0)

Put another way, n % 2 is 0 for positive and negative even numbers and something not even must be odd (which is what you are testing).

CodePudding user response:

This is the correct way:

while (number != 0 && (rest%2 == 1 || rest%2 == -1))

CodePudding user response:

Have a look at Java operator precedence here https://introcs.cs.princeton.edu/java/11precedence/

If I understand correctly you want to enter the loop in two cases:

  • number != 0 && rest%2 == 1

OR

  • rest%2 == -1

If that's true consider using parentheses:

while ((number != 0 && rest%2 == 1) || rest%2 == -1)
  • Related