Java基礎四

來源:互聯網
上載者:User

標籤:++   成績   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基礎四

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.