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

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

问题描述

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

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

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

有没有人知道如何将5行以上的短格式写入一行。 ..

does anyone know how to write short form for above 5 lines into one line...

推荐答案

使用三元运算符:

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

我认为你有条件倒退 - 如果它是null,你想要的值是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天全站免登陆