如何将此语句转换为三元语句?

How can I transform this statement into a ternary?

我正在尝试将一个简单的 if/else 语句转换为三元语句以供练习,但我遇到了麻烦。据我了解,逻辑是:

condition ? (action to take if condition is true) : (action if false);

我的条件是if(result == 8).

我已经试过了:

result == 8 ? return true : return false;

result = 8 ? return true : return false;

这是我的代码,我想转换它的结尾

public boolean sum28(int[] nums) {

    int result = 0;
    for(int i=0; i<nums.length; i++) {
        if(nums[i] == 2) {
            result+=2;
        }
    }
    if(result == 8) {
        return true;
    }
    return false;
}

我遇到类型不匹配问题:当我只使用 1 个等号时无法从 int 转换为 boolean,而当我使用两个等号时得到无效标记“==”。

I've already tried: result == 8 ? return true : return false;

你离得不远了。 == 结果是一个布尔值,所以你只需要:

return result == 8;

之所以有效,是因为您已经有了想要 return 的值(truefalse);这是 result == 8.

的结果

同样,如果你的原件是相反的 (if (result == 8) { return false; } else { return true; }),你会使用 !=:

// If you wanted the opposite
return result != 8;

在更一般的情况下,假设您想要 return "A" if result == 8"B" 否则。你会这样做:

// If you wanted to return "A" (if result == 8) or "B" (if not)
return result == 8 ? "A" : "B";

正确的语法是

return (result == 8) ? true : false;

但在这里你可以

return result == 8;
condition ? (action to take if condition is true) : (action if false);

三元运算符不能完全替代 if/else。两个选项必须是表达式,而不是语句。最好将其视为:

condition ? (result if true) : (result if false)

运算符的结果是一个值,然后可以在更大的语句中使用。要在 return 语句中使用它,您需要将 return 放在前面。

return result == 8 ? true : false;

请注意,这是没有三元运算符的更简单的写法。

return result == 8;