Java 将三元运算转换为if/else语句?
我在Java中有以下布尔方法,但我不能理解它的返回语句,因为它使用三元运算。有人能把它重写成if/else语句吗?这样我就能更好地理解三元运算在做什么Java 将三元运算转换为if/else语句?,java,Java,我在Java中有以下布尔方法,但我不能理解它的返回语句,因为它使用三元运算。有人能把它重写成if/else语句吗?这样我就能更好地理解三元运算在做什么 public boolean collidesWith(Rectangle object){ return (isDestroyed)? false:hitbox.intersects(object); } 三元运算符是编写if-else语句的缩写。它的一般用途是 <boolean condition to eva
public boolean collidesWith(Rectangle object){
return (isDestroyed)? false:hitbox.intersects(object);
}
三元运算符是编写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>
首先,我将如何编写您发布的方法(添加空格): 以下是您要查找的其他if:
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);
}
是的,我能。但我不会这么做,因为你需要了解它的含义,而且目前它比使用
if else
要好得多。什么是“更好得多”,学习一个新事物或使用一个结构胜过另一个?如果是后者,那么在这种特殊情况下,或者当变量的赋值依赖于布尔表达式时,我同意你的观点。不过,在所有其他情况下,我会小心地说一种构造比另一种更好。这取决于很多事情,尤其是作者在特定环境下发现的可读代码。顺便说一句,不需要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);
}
public boolean collidesWith(Rectangle object) {
return isDestroyed ?
false :
hitbox.intersects(object);
}