简体   繁体   English

以下代码段未产生预期结果

[英]Following snippet doesn't produce expected result

I found this in one of the Java programming quiz question. 我在Java编程测验问题之一中找到了这一点。

 public class Calculator { public static void main(String[] args) { int i = 0; Calculator c = new Calculator(); System.out.print(i++ + c.opearation(i)); System.out.print(i); } public int operation(int i) { System.out.print(i++); return i; } } 

Executing above snippet gives me the result of 121 . 执行上面的代码片段可以得到121的结果。 I'm expecting it to be 111 . 我期望是111 I'll explain how I interpreted it. 我将解释如何解释它。

+ addition operator would get executed from right to left (ref: operator precedence ). +加法运算符将从右到左执行(参考: 运算符优先级 )。 So, c.operation(0) is invoked first and it prints the value 1 instead I'm expecting the value to be 0 since System.out.print prints the value of i first and then increments the i value since it is a post increment operator. 因此, c.operation(0)调用c.operation(0)并输出值1但我期望该值为0因为System.out.print输出i的值,然后递增i的值,因为它是一个后缀增量运算符。

Secondly, the i value 1 is returned to the main and the statement System.out.print(i++ + 1) gets executed now. 其次,将i值1返回到main并立即执行语句System.out.print(i++ + 1) And since i has post increment operator it should have executed like 0 + 1 and produced the result 1 insted it printed result as 2 . 而且由于i有后递增运算符,它应该像0 + 1一样执行,并产生结果1 ,将其打印结果作为2

Thirdly, the i value is now incremented to 1 and this gets printed as expected. 第三, i值现在增加到1 ,并按预期方式打印。

In short, I'm expecting the value to be printed as 011 but I got the result as 121 . 简而言之,我期望将值打印为011但结果为121 I'm not sure where my interpretation goes wrong. 我不确定我的解释哪里出错了。

Additive Operators 加法运算符

The additive operators have the same precedence and are syntactically left-associative (they group left-to-right). 加法运算符具有相同的优先级,并且在语法上是左关联的(它们的组从左到右)。


int i = 0;
System.out.print(i++ + c.operation(i));
  1. evaluate i++ , get left operand 0 , and increment i to 1 . 计算i++ ,获得左操作数0 ,并将i递增为1

  2. pass i(1) to c.operation(i) , execute System.out.print(i++) . i(1)传递给c.operation(i) ,执行System.out.print(i++) Print 1 then return 2 (right operand). 打印1然后返回2 (右操作数)。

  3. i++ + c.operation(i) ---> 0 + 2 , print 2 . i++ + c.operation(i) ---> 0 + 2打印2

  4. print 1 . 打印1

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

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