代表語句:while , do while ,for
循環語句用于當對某些語句需要執行很多次時,就使用循環結構
while
while(條件表達式)
{
執行語句;
}
int x = 1;
while(x<3)//while(x<3); 不出現結果,程式一直在問x是否小于3
{
System.out.println("x="+x);
x++;
}
System.out.println("hello world!");
do while
do
{
執行語句;
}while(條件表達式);
int y=4;
do
{
System.out.ptintln("y="+y);
y++;
}
while(i<3);//隻輸出一次結果
while 和 do while 的差別
do while :無論條件是否滿足,循環體至少執行一次
for
for (初始化表達式;循環條件表達式;循環後的操作表達式)
{
執行語句;(循環體)
}
for(int x=1;x<3;x++)
{
System.out.println("x="+x);
}
/*
1.int x=1 2.x<3 3.System.out.println("x="+x) 4.x++
初始化表達式隻執行一次
*/
for 和 while 的差別
當for循環語句結束,其内的變量會及時被釋放掉(就是說這個語句執行完,變量就消失,不能用了)
而while不會
for(int x=1;x<11;x++)
{
System.out.println("x="+x);
}
System.out.println("x......."+x);//錯誤,x找不到,因為for循環語句執行完之後,其内定義的變量消失
int y=1;
while(y<3)
{
System.out.println("y="+y);
y++;
}
System.out.println("y....."+y);