標籤:c++ out 結構 用法 ++i static 局部變數 stl 聲明
Java有三種迴圈結構:
1.while 迴圈
while迴圈的基本表達方式:
while(布林運算式){
//迴圈內容
}
只要布林運算式==True,迴圈就會一直執行
e.g1:
class TestLoop{ public static void main(String args[]){ int i = 10; while(i < 20){ System.out.print("value of x:" + i); i++; System.out.print("\n"); } }}/*輸出結果:value of x:10value of x:11value of x:12value of x:13value of x:14value of x:15value of x:16value of x:17value of x:18value of x:19*/
2.do...while 迴圈
while迴圈,若不滿足條件則不能迴圈;有時我們需要不滿足條件,也至少執行一次
do...while 迴圈和while很相似,但do...while 迴圈至少會執行一次
do...while 迴圈的表達方式:
do{//迴圈內容}while(布林運算式);
備忘:
布林運算式在迴圈體的後面,所以在檢測布林運算式之前已經執行一次。
若運算式始終為T,則do後面的迴圈內容會一直執行 直到運算式==F
e.g2:
class TestLoop{ public static void main(String args[]){ int i = 10; do{ System.out.print("value of x:" + i); i++; System.out.print("\n"); }while(i < 20); } }//輸出內容和e.g1一樣
3.for 迴圈
for迴圈可以使一些迴圈結構變的更簡單
for迴圈執行的次數是執行前就確定的 具體格式如下:
for(初始化A;布林運算式B;更新C){ D運算式;//迴圈內容}//執行順序:A>>B(滿足)>>D>>C>>B(不滿足跳出for迴圈)
e.g3:
class TestLoop{ public static void main(String args[]){ for(int i = 10;i < 20;++i){ System.out.print("value of x:" + i); System.out.print("\n"); } } }//輸出內容和e.g1一樣
數組的for迴圈用法:
for(聲明語句 : 運算式){ //代碼句子}
聲明語句:聲明新的局部變數,該變數的類型必須和數組元素的類型匹配。其範圍限定在迴圈語句塊,其值與此時數組元素的值相等。
運算式:運算式是要訪問的數組名,或者是傳回值為數組的方法。
e.g4:
class TestArrLoop{ public static void main(String args[]){ int [] ages = {10,20,30,40,50}; for(int age:ages){ System.out.print(age); System.out.print(","); } System.out.print("\n"); String [] names = {"Lili","Lucy","HanMeiMei","LiLei","Jim"}; for(String name:names){ System.out.print(name); System.out.print(","); } }}/*輸出結果:10,20,30,40,50,Lili,Lucy,HanMeiMei,LiLei,Jim,*/
break & continue 關鍵字(用法和C/C++相同)
1.class TestLoop{ public static void main(String args[]){ int [] ages = {10,20,30,40,50}; for(int age : ages){ if(age == 30){ break; } System.out.print(age); System.out.print("\n"); } } }/*輸出結果:1020*/2.class TestLoop{ public static void main(String args[]){ int [] ages = {10,20,30,40,50}; for(int age : ages){ if(age == 30){ continue; } System.out.print(age); System.out.print("\n"); } } }/***輸出結果:跳出==30直接執行下一個**10204050*/
整理Java基礎知識--迴圈結構