while
class WhileDemo{
public static void main(String[] args){
/*
定義初始化表達式
while(條件表達式){
循環體(執行語句)
}
*/
int x = 1;
while(x<3){
System.out.println("x="+x);
x++;//與++x;獨立運算的時候沒區別,a= x++;就有區別了
//x+=2;//打印所有奇數
}
}
}
do while
class DoWhileDemo{
public static void main(String[] args){
int x = 1;
do{
System.out.println("do:x"+x);
x++;
}
while(x<0);
int y = 1;
while(y<0){
System.out.println("y="+y);
y++;
}
//x執行一次輸出,y不輸出
/*
while:先判斷條件,只有條件滿足才執行循環體
do while:先執行循環體,再判斷條件條件滿足再執行循環體
*/
}
}
for
class ForDemo{
public static void main(String[] args){
/*
for(初始化表達式:循環條件表達式;循環后的表達式)
{
執行語句
}
*/
for(int x = 0; x < 3; x++){
System.out.println("x="+x);//判斷語句符合執行循環體,再++
}
}
}
while的變量初始化作用域在外面,for在內部,執行完畢變量在內存中被釋放。為循環增量存在控制循環次數用for體現,內存相對優化
總結:
什么時候使用循環結構?
當要對某些語句執行很多次時使用
無線循環最簡單表現形式:
for(;;){}//默認判斷語句為true
while(true){}