Java if 语句的简写形式 [英] Short form for Java if statement

查看:40
本文介绍了Java if 语句的简写形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know there is a way for writing a Java if statement in short form.

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

有谁知道上面5行的简写怎么写成一行?

Does anyone know how to write the short form for the above 5 lines into one line?

推荐答案

使用三元运算符:

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

我认为你有倒退的条件 - 如果它为空,你希望值为N/A".

I think you have the conditions backwards - if it's null, you want the value to be "N/A".

如果城市为空怎么办?在这种情况下,您的代码 * 命中了.我会添加另一张支票:

What if city is null? Your code *hits the bed in that case. I'd add another check:

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

这篇关于Java if 语句的简写形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆