09語句的巢狀以及跳轉語句
阿新 • • 發佈:2020-10-10
語句
- 無限迴圈語句
- 語句的巢狀
- 跳轉語句
一、無限迴圈
1.最簡單的無限迴圈格式
//第一種 while(true){ } //第二種 for( ; ; ){ }
2.無限迴圈存在的意義:是不知道需要迴圈多少次,而是根據某些條件來控制迴圈。
二、迴圈語句的巢狀
1.迴圈巢狀:指在一個迴圈語句的迴圈體中再定義一個迴圈語句的語法結構。
2.舉例for迴圈巢狀輸出九九乘法表
public class Demo{ public static void main(String[] args) { int x = 0; int y = 0; for(x=0;x<=9;x++) { for(y=1;y<=x;y++) { System.out.print(x + "*" + y + "=" + x * y + "\t"); } System.out.println(); } } }
三、跳轉語句
1.跳轉語句分為兩種,break語句和continue語句
2.break語句:在switch條件語句和迴圈語句中都可以使用break語句。
a.當它出現在switch條件語句中時,作用是終止某個case並跳出switch結構。
public class Demo { public static void main(String[] args) { int week = 6; switch (week) { case 1: System.out.println("今天是星期一,工作日"); break; case 2: System.out.println("今天是星期二,工作日"); break; case 3: System.out.println("今天是星期三,工作日"); break; case 4: System.out.println("今天是星期四,工作日"); break; case 5: System.out.println("今天是星期五,工作日"); break; case 6: System.out.println("今天是星期六,休息日"); break; case 7: System.out.println("今天是星期天,休息日"); break; default: System.out.println("無法判斷"); break; } } }
b.當它出現在迴圈語句中,作用是跳出迴圈語句,執行後面的程式碼
public class Demo { public static void main(String[] args) { int x = 1; while (x <= 4) { System.out.println("x = " + x); if (x == 3) { break; } x++; } } }
3.continue語句
a.continue語句用在迴圈語句中,它的作用是終止本次迴圈,執行下一次迴圈。
//求1~100內所有奇數的和 public class Demo { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 100; i++) { if (i % 2 == 0) { //驗證i是否為偶數 continue; // i是偶數則結束本次迴圈 } sum += i; // 實現sum和i的累加 } System.out.println("sum = " + sum); } }