为什么这个if语句在NetBeans 8.2中不是重复的

时间:2018-04-21 09:26:39

标签: java netbeans

我在java类中编写了一个方法,如下所示:

public boolean checkPlace() {
    if (this.PlaceName.equals("Name Place"))
        return true;
    else return false;
}

我想知道为什么它不是还原剂。

我可以只写return if语句吗?

提前致谢。

2 个答案:

答案 0 :(得分:0)

你可以写:

public boolean checkPlace() {
    return PlaceName.equals("Name Place");
}

答案 1 :(得分:0)

一般来说是多余的。最佳做法是写

if (this.PlaceName.equals("Name Place")) {
    return true;
}
return false;

或者,如果这不仅仅是一个虚拟的例子

return this.PlaceName.equals("Name Place")

如果您更习惯于使用其他语言的类似表达式的语法,那么Java会允许您编写

return  if (this.PlaceName.equals("Name Place")) true else false;

但它确实支持三元表达式,在这种情况下你必须确保你只有2个分支而不是更多。

return this.PlaceName.equals("Name Place") ? true : false;