[英]Loop runs one more time than I expected
class BlankIt{
public static void main(String[] args) {
int i = 10, j = 20;
while(i++ < --j){
System.out.println("\n " + i + " " + j);
}
System.out.println("\n " + i + " " + j);
}
}
The preceding output is 16 14
.前面的 output 是
16 14
。 Why is that happening??为什么会这样?? The loop stops when the condition reaches
15 < 15
.当条件达到
15 < 15
时,循环停止。 Please help me out!!请帮帮我!!
The increment of i
, being a post-increment, will occur after the comparison is evaluated, j
, on the other hand, being a pre-decrement will occur before the comparison is evaluated: i
的增量,作为后增量,将在比较评估之后发生, j
,另一方面,作为预减量,将在比较评估之前发生:
10 < 19 (true)
11 < 18 ...
12 < 17 ...
13 < 16 ...
14 < 15 ...
15 < 14 (false)
After the evaluation of the last comparison, i
will be incremented one more time and will have the value of 16
, j
since it was already decremented will remain 14
.在对最后一次比较进行评估之后,
i
将再增加一次,并将具有16
的值, j
因为它已经减少了,所以将保持14
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.