三元运算符 - JAVA [英] Ternary Operator - JAVA

查看:146
本文介绍了三元运算符 - JAVA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更改此内容:

if(String!= null) {

    callFunction(parameters);

} else {

    // Intentionally left blank

}

...给一个三元运算符?

...to a ternary operator?

推荐答案

嗯,<$ Java中的c $ c>三元运算符就像这样......

Well, the ternary operator in Java acts like this...

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

...另一种看待它的方式......

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






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


You question is kind of vague and we have to assume here.


  • 如果(仅限于) callFunction(。 ..)声明非空返回值(对象 String int double 等等。) - 它好像它不能通过你的代码 - 然后你可以这样做...

  • If (and only if) callFunction(...) declares a non-void return value (Object, String, int, double, etc..) - it seems like it does not do that via your code - then you could do this...

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


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

  • If callFunction(...) does not return a value, then you cannot use the ternary operator! Simple as that. You will be using something that you don't need.


    • 请发布更多代码以解决任何问题

    尽管如此,三元运营商应代表其他任务只有!! 你的代码似乎没有这样做,所以你不应该这样做。

    Nonetheless, ternary operator should represent alternative assignments only!! Your code does not seem to do that, so you should not be doing that.

    这是他们应该如何工作...

    This is how they should work...

    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())
           : ("");
    






    既然你似乎可能试图将此代码重构为单行代码,我添加了以下内容


    Since it seems like you might be trying to just refactor this code to be a one-liner, I have added the following

    此外,如果您的错误 - 子句真的是空的,那么你可以这样做...

    Also, if your false-clause is truely empty, then you can do this...

    if (string != null) {
    
        callFunction(...);
    
    } // Take note that there is not false clause because it isn't needed
    

    OR

    if (string != null) callFunction(...);  // One-liner
    

    这篇关于三元运算符 - JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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