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

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

问题描述

是否可以更改此设置:

if(String!= null) {

    callFunction(parameters);

} else {

    // Intentionally left blank

}

...到三元运算符?

推荐答案

好吧,Java 中的 三元运算符 就像这样......

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(...) 声明了一个 non-void 返回值 (ObjectStringintdouble 等.)-似乎它不是通过你的代码 - 那么你可以这样做......

  • 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

    另外,如果你的 false-clause 真的是空的,那么你可以这样做......

    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
    

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

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

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