[英]Java do while loop increment
int i = 10;
int j = 0;
do {
j++;
System.out.println("loop:" + j);
while (i++ < 15) { //line6
i = i + 20;
System.out.println(i);
} ;
} while (i < 2);
System.out.println("i_final:" + i);
Output:输出:
loop:1
31
i_final:32
Why the i_final
is 32
and not 31
?为什么
i_final
是32
而不是31
? As we can see the do_while
loop has executed only once, so line 8 should also have executed only once, hence incrementing the value of "i" by 1. When did 31
increment to 32
?我们可以看到
do_while
循环只执行了一次,所以第 8 行也应该只执行一次,因此将“i”的值增加 1。 31
什么时候增加到32
?
While loop will be executed twice before its break. While 循环将在中断前执行两次。
while (i++ < 15) { //line6
i = i + 20;
System.out.println(i);
} ;
First it increment to 11 .首先它增加到 11 。
Check with 15. Returns true.检查 15。返回 true。
Now it increments to 31. ( i = i + 20
)现在它增加到 31。 (
i = i + 20
)
now again while loop .现在再次 while 循环。
it increments the value .它增加了价值。
First time when while loop condition is checked i=11, after that i is incremented by 20, so i=31.第一次检查 while 循环条件时 i=11,之后 i 增加 20,所以 i=31。 Then while condition is checked again, when found that 31 < 15 is false i is still incremented by 1. So i =32
然后当再次检查条件时,当发现 31 < 15 为假时,i 仍然增加 1。所以 i =32
when you are doing a while loop as (i++ < 15) , it checks the condition and stop the loop if i++ is < 15 , But here when you do a do while loop j++ the loop goes 2 times and when it comes to while (i++ < 15) it increaments the value of i by 1 and stops... so in second loop the value of i increases by one but the function inside the while loop remains the same as it stops when i++ is > than 15当您执行 while 循环为 (i++ < 15) 时,它会检查条件并在 i++ 为 < 15 时停止循环,但是在这里,当您执行 do while 循环 j++ 时,循环会进行 2 次,当涉及到 while ( i++ < 15) 它将 i 的值增加 1 并停止...所以在第二个循环中 i 的值增加 1 但 while 循环中的函数保持不变,当 i++ 大于 15 时它停止
IF you do the following you will get 31如果您执行以下操作,您将获得 31
int i = 10;
int j = 0;
do {
j++;
System.out.println("loop:" + j);
while (i < 15) { //line6
i++
i = i + 20;
System.out.println(i);
} ;
} while (i < 2);
System.out.println("i_final:" + i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.