简体   繁体   中英

Why does this return true?

I recently started to teach myself Java, after playing around with CodingBat I am left with an extremely basic question. Why is this returning "true"?

a = 1, b= -1, negative = true

public boolean posNeg(int a, int b, boolean negative) {
  if(!negative && a <= 0 && b >= 0 || a >= 0 && b <= 0){
    return true;
  }else if(negative && a <= 0 && b <= 0){
    return true;
  }
  return false;
}

In:

!negative && a <= 0 && b >= 0 || a >= 0 && b <= 0

the higher precedence of && than || means it is the same as:

(!negative && a <= 0 && b >= 0) || (a >= 0 && b <= 0)

The conditional-or operator ( || ) will return true if either of its operands are true:

  • !negative && a <= 0 && b >= 0 is false, because negative is false (as is b >= 0 , but that's not evaluated);
  • a >= 0 && b <= 0 is true

Hence the expression is true , and so the if statement is executed, meaning that true is returned.

because :

if (!negative && a <= 0 && b >= 0 || a >= 0 && b <= 0) {
//---(false)------(true)----(false)-----(true)----(true)

The trick is with || :

false && true && false -> false
true && true -> true

(false && true && false) || (true && true) ----> true
     false               ||     true       ----> true

在您的第一个if if(!negative && a <= 0 && b >= 0 || a >= 0 && b <= 0){ A大于0,b小于0的情况下,返回true。

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