将三元运算转换为if / else语句?

时间:2014-08-31 07:38:46

标签: java

我在Java中有以下布尔方法,但我无法理解它的return语句,因为它使用了三元运算。任何人都可以将其重写为if / else语句,以便我能更好地理解三元操作的作用吗?

    public boolean collidesWith(Rectangle object){
    return (isDestroyed)? false:hitbox.intersects(object);
    }

3 个答案:

答案 0 :(得分:4)

三元运算符是编写if-else语句的简写。它的一般是

<boolean condition to evaluate> ? 
    <return value if condition is true - i.e., the "if" branch > : 
    <return value is condition is false - i.e., the "else" branch>

所以,如果你展开你展示的方法,你就会得到:

public boolean collidesWith(Rectangle object){
    if (isDestroyed) {
        return false;
    } else {
        return hitbox.intersects(object);
    }
}

答案 1 :(得分:2)

首先,我将如何编写您发布的方法(添加空格):

public boolean collidesWith(Rectangle object) {
    return isDestroyed ? false : hitbox.intersects(object);
}

以下是你要找的if-else:

public boolean collidesWith(Rectangle object) {
    if (isDestroyed) {
        return false;
    }
    else {
        return hitbox.intersects(object);
    }
}

..还是有点简化:

public boolean collidesWith(Rectangle object) {
    if (isDestroyed)
        return false;

    return hitbox.intersects(object);
}

您也可以让三元运算符看起来有点像if-else:

public boolean collidesWith(Rectangle object) {
    return isDestroyed ?
        false :
        hitbox.intersects(object);
}

答案 2 :(得分:-2)

public boolean collidesWith(Rectangle object){
      if(isDestroyed)   
          return false;
      else              
          return hitbox.intersects(object);

}
相关问题