(1)在循环中使用i++和++i的区别
while循环使用i++
1 public static void main(String[] args) { 2 3 int count = 0; 4 int max = 5; 5 6 while(count++<max){ 7 System.out.println(count); 8 } 9 10 System.out.println(count); 11 }
代码运行到line6之前count=0,while(count++<max)可以理解为连续执行的两条语句while(count<max)和count=count+1。所以会先判断0<5?,然后进入循环块之前count变成1。依次理解,最后几个状态是count=4,count<5?,count=count+1=5,进入循环块输出5;此时count=5,count<5?,count=count+1=6,不进入循环块。循环的代码执行了5次。
这里需要注意的是:count在循环代码块中(line6-9)最后值是max,结束循环后的值是max+1,循环执行了max次。
所以输出
1 2 3 4 5 6
while循环使用++i
1 public static void main(String[] args) { 2 3 int count = 0; 4 int max = 5; 5 6 while(++count<max){ 7 System.out.println(count); 8 } 9 10 System.out.println(count); 11 }
代码运行到line6之前count=0,while(++count<max)可以理解为连续执行的两条语句count=count+1和while(count<max)。所以第一次进入循环时,count=count+1=1,1<5?,然后进入循环块输出1,最后几个状态是count=4,然后进入line6,count=count+1=5,5<5?,不进入循环块。循环的代码只执行了4次。
这里需要注意的是:count在循环代码块中(line6-9)最后值是max-1,结束循环后的值是max,循环执行了max-1次。
所以输出
1 2 3 4 5
for循环中i++
public static void main(String[] args) { int count = 0; int max = 5; for(;count<max;count++){ System.out.println(count); } System.out.println(count); }
输出
0 1 2 3 4 5
for循环中++i
public static void main(String[] args) { int count = 0; int max = 5; for(;count<max;++count){ System.out.println(count); } System.out.println(count); }
输出
0 1 2 3 4 5
for循环中使用count++和++count结果一样,都循环了max次,因为for循环执行判断语句count<max后会先进入循环块执行,执行循环块之后再执行count++(或者++count),这里没什么区别进入循环块前count都会自增1。
注意:for循环count的输出从0开始,而while循环是从1开始。
(2)更新中...