简体   繁体   English

?运算符不起作用

[英]? Operator Does Not Work

How come this is not possible? 怎么这不可能? I am getting illegal start of expression. 我开始表达非法行为。

(s1.charAt(i) == ' ') ? i++ : break;

The thing to understand here is that the ?: operator is used to return a value . 这里要理解的是?:运算符用于返回一个值 You're basically calling a function that looks like this in that line: 你基本上是在这一行调用一个看起来像这样的函数:

anonymous function:
    if(s1.charAt(i) == ' '):
        return i++;
    else:
        return break;

Makes no sense, right? 没有意义,对吧? The ?: operator was only designed as a shorthand for if/else return statements like the above, not a replacement of if/else altogether. ?:运算符仅被设计为if / else返回语句的简写,如上所述,而不是if / else的替换。

You cannot use break in part of a ternary conditional expression as break isn't an expression itself, but just a control flow statement. 您不能在三元条件表达式的一部分中使用break ,因为break不是表达式本身,而只是一个控制流语句。

Why not just use an if-else construct instead? 为什么不使用if-else结构呢?

if (s1.charAt(i) == ' ') {
    i++;
} else {
    break;
}

The ternary operator is an expression, not a statement. 三元运算符是表达式,而不是语句。 Use if ... else ... for this. 使用if ... else ...为此。

Of course it works. 当然有效。 But it's an operator. 但它是一个运营商。 Since when was a statement such as 'break' an operand? 从什么时候开始,如'break'一个操作数?

I recommend avoiding the ternary (?:) operator EXCEPT for simple assignments. 我建议避免使用三元(?:)运算符EXCEPT进行简单赋值。 In my career I have seen too many crazy nested ternary operators; 在我的职业生涯中,我见过太多疯狂的嵌套三元运算符; they become a maintenance headache (more cognitive overload - "don't make me think!"). 它们成为一种维持头痛(更多的认知过载 - “不要让我思考!”)。

I don't ban them on my teams, but recommend they are used judiciously. 我并不禁止他们加入我的团队,但建议明智地使用它们。 Used carefully they are cleaner than a corresponding if/else construct: - 仔细使用它们比相应的if / else结构更清洁: -

public int ifFoo() {
    int i;

    if( isSomethingTrue()) {
        i = 5;
    }
    else {
        i = 10;
    }

    return i;
}

Compared to the ternary alternative: - 与三元替代方案相比: -

public int ternaryFoo() {
    final int i = isSomethingTrue()
                ? 5
                : 10;

    return i;
}

The ternary version is: - 三元版本是: -

  • Shorter
  • Easier to understand (my opinion, of course!) 更容易理解(我的意见,当然!)
  • Allows the variable to be "final"; 允许变量为“最终”; which simplifies code comprehension; 这简化了代码理解; in a more complex method, someone reading the code knows no further code will try and modify the variable - one thing less to worry about. 在一个更复杂的方法中,有人阅读代码知道没有其他代码会尝试修改变量 - 一件事要少担心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM