while、do-while、for 循環的區別
相同點
都遵循循環四要素,即初始化循環變量、循環條件、循環體、更新循環變量。
不同點
- while 和 do-while 適用於循環次數不確定的場景;for 循環適用於循環次數確定的場景。
- while 和 for 是先判斷循環條件,再執行循環體;do-while 循環是先執行循環體,再判斷循環條件。
分別使用 while、do-while、for 循環輸出 10 以內所有奇數。
public class Test {
public static void main(String[] args) {
//while循環
// int num = 0;
// while(num <= 10){
// if(num%2!=0){
// System.out.println(num);
// }
// num++;
// }
//do-while循環
// int num = 0;
// do{
// if(num%2!=0)System.out.println(num);
// num++;
// }while (num <= 10);
//for循環
for (int num = 0;num<=10;num++){
if(num%2!=0) System.out.println(num);
}
}
}