简体   繁体   中英

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 . Why is that happening?? The loop stops when the condition reaches 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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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