gpt4 book ai didi

java - 三元运算符

转载 作者:IT老高 更新时间:2023-10-28 21:14:11 25 4
gpt4 key购买 nike

是否可以更改:

if (string != null) {
callFunction(parameters);
} else {
// Intentionally left blank
}

到三元运算符?

最佳答案

嗯,Java中的三元运算符是这样的......

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

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

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

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

  • 如果 (且仅当) callFunction(...) 声明一个 non-void 返回值( ObjectStringintdouble 等)- 似乎它没有通过你的代码 - 那么你可以这样做......

    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 - 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25163713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com