简体   繁体   中英

Condition for while loop doesn't work in java

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?

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).

这是正确的方法:

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM