Java do loop increment

int i = 10; 
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 I_ Final is 32 instead of 31? As we can see, do_ The while loop is executed only once, so line 8 should also be executed only once, so increment the value of "I" by 1 Increased from 31 to 32?

Solution

When you do a while loop (I < 15), it checks the conditions and stops the loop. If I am < 15, but here when you do a while loop J, the loop becomes 2 times, and when it becomes while (I < 15), it increases the value of I by 1 and stops So in the second loop, the value of I increases by one, but the function in the while loop remains unchanged. When it is >, it stops for more than 15

If you do the following, you will get 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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>