gpt4 book ai didi

java - 评估尊重括号和优先级 - java

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:08:25 24 4
gpt4 key购买 nike

根据 Java 语言规范:

计算尊重括号和优先级

除了使用像这样的数学运算:

int i = 3;
int j = 3 * (9 + 3);
System.out.println(j); //results to 36

还有适用此规则的其他示例吗?我尝试使用

int i = 0;
int z = 0;
if(i++ < 5 || (++z <0 && 5 > z++) || 6 < ++i){
System.out.println("Routed here");
}
System.out.println("i: " + i);
System.out.println("z: " + z);

但结果是 i: 1 和 z:0。看来那个if例子的求值还是从左到右。

最佳答案

|| , Java 在计算表达式时使用了短路的概念。因此,在此:

if(i++ < 5 || (++z <0 && 5 > z++) || 6 < ++i){

自第一个表达式i++ < 5返回 true,因此表达式的其余部分将不会被评估,即从未访问过,因此只会改变 i 的值没有其他东西。

引自 Java 文档:

The Conditional OperatorsThe && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.&& Conditional-AND|| Conditional-ORThe following program, ConditionalDemo1, tests these operators:
class ConditionalDemo1 {

public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1))
System.out.println("value1 is 1 OR value2 is 1");
}
}

关于java - 评估尊重括号和优先级 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com