繁体   English   中英

在 java 澄清中使用 += 和三元运算符

[英]using += and ternary operator in java clarification

我正在为即将到来的考试做一些练习题,遇到了一个我和我的 class 队友似乎都能理解的问题。 如下:

其中所有变量都是 int 或 int 数组。

得分+=(轮次[i])? 我+开始:0

三元运算符如何在 java 中使用 +=? 这是我的理解:

所以它是 score += round[i] == i+start 或 == 0。

这是一个正确的理解吗?

亲切的问候,詹姆斯

与运算符的任何组合一样,这是运算符优先级和(在运算符具有相同优先级的情况下)关联性的问题。 在 Java 中,简单赋值和所有运算符/赋值运算符共享最低优先级。 三元运算符是下一个更高优先级的唯一占用者。 因此,您的表达式相当于

score += ((rounds[i]) ? (i + START) : 0)

也就是说,对三元表达式求值,其结果是+=的右侧操作数。

正如其他人所观察到的,如果rounds[i]的类型为int ,则在 Java 中无效,尽管在 C 中可以。 但是如果rounds[i]boolean的数组,则表达式在 Java 中可能是明智的,或者可以像这样重写...

score += ((rounds[i] != 0) ? (i + START) : 0)

...假设需要对 integer rounds[i]的 C 风格 boolean 解释。

score += (some condition which is true or false) ? value to add if true : value to add if false;

我们可以试试。

    int START = 3;

    int score = 0;
    boolean[] rounds = { true, false };
    for (int i = 0; i < rounds.length; i++) {
        score += (rounds[i]) ? i + START : 0;
        System.out.format("i is %d, score is %d%n", i, score);
    }

Output:

 i is 0, score is 3 i is 1, score is 3

所以第一次通过循环i是 0 并且rounds[i]true 在这种情况下 Java 添加iSTART得到 3 并将其添加到score 第二次i1并且rounds[i]false ,所以只添加了 0 。

您询问的语句增加了score的值。 如果rounds[i]可以评估为 true ,则添加的值是i + START ,如果是false ,则添加 0 。 如果iSTART都是数字,则会添加一个数字。 如果score是数字,添加 0 通常没有区别,因此您可能会认为该语句仅在rounds[i]为真时才添加值。

所以它是 score += round[i] == i+start 或 == 0。

不,语句中没有隐含的==比较(正如其他人所说,它要求rounds[i]是 Boolean 值,真或假)。

三元运算符?:使用如下:

  • a = bolean_expression? 如果为真,则为:否则为假。
        int start = 5;

        // In this case, start was added to itself to obtain 10.                
        start += true ? start  : 0;
        System.out.println(start); // prints 10

        // with out the compound assignment operator (+=) the
        // expression should be enclosed in () 
        start = start + (true ? start : 0);
        System.out.println(start); // prints 20

在上述情况下,如果 boolean 为 false,则start始终具有值5 ,因为每次都会添加0

暂无
暂无

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

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