java-我期望输出为40但我得到30

class Tester {
    public static void main(String[] arg) {
        byte b=10;
        b +=(b<127)?b>-128? b+=10 :0 :5;
        System.out.println(b);
    }
}

我知道条件评估为真,并将控制权设为b = 10
所以现在逻辑上b = b = 10;是将b的值与10相加得出20,将值赋给b.现在,我无法对其进行进一步评估.

解决方法:

JLS 15.7.1. Evaluate Left-Hand Operand First有一个类似的例子:

If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable’s value for use in the implied binary operation.

Example 15.7.1-2. Implicit Left-Hand Operand In Operator Of Compound Assigment

In the following program, the two assignment statements both fetch and remember the value of the left-hand operand, which is 9, before the right-hand operand of the addition operator is evaluated, at which point the variable is set to 3.

class Test2 {
    public static void main(String[] args) {
        int a = 9;
        a += (a = 3);  // first example
        System.out.println(a);
        int b = 9;
        b = b + (b = 3);  // second example
        System.out.println(b);
    }
}

This program produces the output:

12
12

因此,在您的情况下,会记住b(10)的原始值并将其添加到三元条件运算符的结果中(由于b = 10的值是该表达式的结果,所以为20),从而得到30.

上一篇:PHP参数化SQL查询特殊运算符


下一篇:PHP中VB的“ AndAlso”等效项是什么?