简体   繁体   English

为什么 jshell 显示这个数字?

[英]Why does jshell show this number?

I am learning java and this logic makes me feel confused.我正在学习 java,这个逻辑让我感到困惑。

Isn't here i=20(+1)+20(+1) ?这里不是i=20(+1)+20(+1)吗?

Why 41 instead of 42 ?为什么是41而不是42

jshell> int i = 20
i ==> 20
jshell> i=i++ + i++
i ==> 41

See this code run at Ideone.com .请参阅在Ideone.com运行的代码。

Effectively, the expression i=i++ + i++;实际上,表达式i=i++ + i++; is equal to i=i++ + i;等于i=i++ + i; . . Why?为什么? The latter i++ result value is never used and is not propagated.后一个i++结果值从不使用,也不会传播。 The result of the postfix addition i++ is used as long as the value i is added later in the expression and the result takes the effect.后缀加i++的结果只要在表达式后面加上值i并且结果生效。 However, after the latter i++ the result value of i is not used.但是,在后面的i++之后,不使用i的结果值。

If you want to achieve the result of 42 , you need to perform the postfix assignment ( i++ ) after the whole result is assigned back to the i variable:如果要实现42的结果,则需要在将整个结果分配回i变量后执行后缀赋值( i++ ):

int i = 20;
i = i++ + i;
i++;
System.out.println(i);

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

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