標籤:++ 成績 tin 16px 輸出 new 方法 color +=
break continue return 的區別
| 關鍵字 |
位置 |
作用 |
| break |
switch和迴圈 |
結束迴圈 |
| continue |
迴圈 |
結束本次迴圈,進行下一次迴圈 |
| return |
用在方法中的任何地方 |
結束方法 |
for迴圈中使用break
1 int score; 2 int sum=0; 3 int i; 4 for (i=1;i<=5;i++){ 5 System.out.println("請輸入成績"); 6 Scanner scanner=new Scanner(System.in); 7 score=scanner.nextInt(); 8 if (score<0){ 9 System.out.println("錄入錯誤,重新輸入");10 break;//結束for迴圈11 }12 13 sum+=score;14 15 16 }17 if (i==6){18 System.out.println("平均成績"+(sum/5));19 }
switch中使用break
1 switch (number){ 2 case 1: 3 System.out.println("正方形"); 4 break; //跳出switch 5 case 2: 6 System.out.println("三角形"); 7 break; 8 case 3: 9 System.out.println("圓形");10 break;11 default:12 System.out.println("輸入錯誤");13 break;14 }
for中使用continue
1 /**輸出1~10的偶數*/ 2 public class Test { 3 public static void main(String[] args) { 4 for (int i=1;i<=10;i++){ 5 if (i%2!=0){ 6 continue; //如果 i 不是偶數,不執行後面的輸出語句,繼續執行for迴圈 7 } 8 System.out.println(i); 9 }10 }11 }
return
1 public class Test { 2 public static void main(String[] args) { 3 a: //此處定義a 4 for (int i=1;i<=5;i++){ 5 for (int j=1;j<=5;j++){ 6 /** 7 * if (i==3){ 8 * // break; //結束內部迴圈 9 * // break a; //結束外迴圈列印輸出最後的結束10 * // return; //結束整個程式,不列印輸出最後的"結束"語句11 * }12 *13 * */14 15 16 if (j==3){17 // continue ;//結束本次內迴圈18 continue a; //結束本次外迴圈19 20 }21 System.out.print(i+"行"+j+"列 ");22 }23 System.out.println();24 }25 System.out.println("結束");26 }27 }
Java基礎四