關鍵字 | 位置 | 做用 |
break | switch和循環 | 結束循環 |
continue | 循環 | 結束本次循環,進行下一次循環 |
return | 用在方法中的任何地方 | 結束方法 |
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 }
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中使用continuespa
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 }
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 }