您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

JAVA 三元运算符

JAVA 三元运算符

好吧,ternary operatorJava中的行为就像这样……

return_value = (true-false condition) ? (if true expression) : (if false expression);

…另一种看待它的方式…

return_value = (true-false condition) 
             ? (if true expression) 
             : (if false expression);

你的问题有点含糊,我们必须在这里假设。

return_value = (string != null) 
             ? (callFunction(...)) 
             : (null);

如果callFunction(…)不返回值,那么你将无法使用三元运算符!就那么简单。你将使用不需要的东西。

请发布更多代码以清除所有问题 尽管如此,三元运算符仅应代表替代分配!!你的代码似乎没有做到这一点,因此你不应该这样做。

这就是他们应该如何工作的…

if (obj != null) {            // If-else statement

    retVal = obj.getValue();  // One alternative assignment for retVal

} else {

    retVal = "";              // Second alternative assignment for retVale

}

这可以转换为…

retVal = (obj != null)
       ? (obj.getValue())
       : ("");

由于你似乎可能试图将代码重构为单一代码,因此我添加了以下内容

另外,如果你的虚假条款确实是空的,那么你可以这样做…

if (string != null) {

    callFunction(...);

} // Take note that there is not false clause because it isn't needed

要么

if (string != null) callFunction(...);  // One-liner
java 2022/1/1 18:15:37 有384人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶