我知道有一种方法可以用简短的形式编写Java if语句。

if (city.getName() != null) {
    name = city.getName();
} else {
    name="N/A";
}

有谁知道如何把以上5行的简写成一行吗?


当前回答

你可以这样让它变得更简单:

name = city.getName() == null ? city.getName() : "N/A"

其他回答

你可以这样让它变得更简单:

name = city.getName() == null ? city.getName() : "N/A"

方法是用三元运算符:

name = city.getName() == null ? city.getName() : "N/A"

然而,我相信你在上面的代码中有一个拼写错误,你的意思是说:

if (city.getName() != null) ...

你可以用简短的形式写出if, else if, else语句。例如:

Boolean isCapital = city.isCapital(); //Object Boolean (not boolean)
String isCapitalName = isCapital == null ? "" : isCapital ? "Capital" : "City";      

这是的缩写形式:

Boolean isCapital = city.isCapital();
String isCapitalName;
if(isCapital == null) {
    isCapitalName = "";
} else if(isCapital) {
    isCapitalName = "Capital";
} else {
    isCapitalName = "City";
}
name = (city.getName() != null) ? city.getName() : "N/A";

为了避免两次调用.getName(),我将使用

name = city.getName();
if (name == null) name = "N/A";