简体   繁体   English

使用三元运算符时出错

[英]Error using a ternary operator

As shown in the following code, I would like to use ternary operator. 如以下代码所示,我想使用三元运算符。 But I am getting an error saying: "; expected" but I think, there is no need to add the semi-colon. 但是,我收到一个错误消息:“;预期”,但我认为,无需添加分号。

Code : 代码

.filter(new Predicate<List<String>>() {
    @Override
    public boolean test(@NonNull List<String> strings) throws Exception {
        List<String> lst = new ArrayList<String>();
        for (String string : strings) {
            Log.i(TAG, ".filter(): string: " + string);
            string.toLowerCase().startsWith("b") ? lst.add(string): continue;
        }
        Log.i(TAG, ".filter(): lsr: " + lst);
        return lst.size() > 0;
    }
})

Ternary operation is used to assign or return values, continue; 三元运算用于分配或返回值, continue; is an instruction, to keep it simple use something like: 是一条指令,为了使其简单易用,请使用以下命令:

if(string.toLowerCase().startsWith("b")) {
    lst.add(string); 
} else {  
    continue;
}

First of all, you cannot use continue in a ternary condition, since continue is a statement, not an expression, as what the ternary condition is expecting. 首先,您不能在三元条件下使用continue ,因为continue是语句,而不是表达式,正如三元条件所期望的那样。 More on the expression statements here (credits to @Andreas ) 此处更多有关表达式语句的信息 (提供给@Andreas

My suggestion instead of trying to try making use of the ternary condition, is to use java streams, since you are already using filter and predicates: 我的建议而不是尝试使用三元条件,而是使用Java流,因为您已经在使用filter和谓词:

.filter(strings -> strings.stream()
                          .anyMatch(string -> string.toLowerCase().startsWith("b")));

This will have the same result you are trying to do with collecting the strings that start with b . 这与您尝试收集以b开头的字符串的结果相同。

The Conditional Operator ? : 条件运算符? : ? : is an expression , not a statement (see JLS 15.25. Conditional Operator ? : ). ? :表达式 ,而不是语句 (请参见JLS 15.25。条件运算符? : :)

Expressions cannot be written as statement, ie the following are both invalid: 表达式不能写为语句,即以下两个都是无效的:

2 + 7;
a == 42 ? foo() : bar();

Note that only some expressions are also valid as statements, and ? : 请注意,只有某些表达式也可用作语句,并且? : ? : is not one of them ( JLS 14.8. Expression Statements ): ? :不是其中之一( JLS 14.8。Expression语句 ):

 ExpressionStatement: StatementExpression ; StatementExpression: Assignment PreIncrementExpression PreDecrementExpression PostIncrementExpression PostDecrementExpression MethodInvocation ClassInstanceCreationExpression 

In addition, the syntax of the Conditional Operator is: 此外,条件运算符的语法为:

 ConditionalOrExpression ? Expression : ConditionalExpression ConditionalOrExpression ? Expression : LambdaExpression 

Meaning that all 3 parts must be expressions , and continue is a statement, not an expression. 这意味着所有3个部分都必须是expressions ,而continue是语句,而不是表达式。

To summarize, ? : 总之, ? : ? : is an expression and cannot be used as a statement, and it can only contain expressions, not statements. ? :是表达式,不能用作语句,并且只能包含表达式,不能包含语句。 It is not a replacement for the if statement. 它不能替代if语句。

So, your code should be written using if statement: 因此,您的代码应使用if语句编写:

for (String string : strings) {
    Log.i(TAG, ".filter(): string: " + string);
    if (string.toLowerCase().startsWith("b")) {
        lst.add(string);
    } else {
        continue;
    }
}

Of course, having a continue statement at the end of the loop is redundant (the loop will continue anyway), so the else can be removed: 当然,在循环末尾使用continue语句是多余的(循环仍将继续),因此可以删除else语句:

for (String string : strings) {
    Log.i(TAG, ".filter(): string: " + string);
    if (string.toLowerCase().startsWith("b"))
        lst.add(string);
}

First of all Ternary operation is used to assign or return values, continue is an instruction. 首先,三元运算用于分配或返回值,continue是一条指令。

string.toLowerCase().startsWith("b") ? lst.add(string): continue;

Replace this line by 替换为

if(string.toLowerCase().startsWith("b"))
     lst.add(string);
else
     continue;

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

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