php中for迴圈遇上return的範例程式碼分享

來源:互聯網
上載者:User
先看下以下方法的列印結果以及傳回值:

public static void main(String[] args) {System.out.println("傳回值:" + testResult());}public static boolean testResult() {for(int i=1; i<=5; i++) {System.out.println("-------------->開始:" + i);if(i == 3) {return true;}System.out.println("-------------->結束:" + i);}return true;}

列印結果:

-------------->開始:1

-------------->結束:1

-------------->開始:2

-------------->結束:2

-------------->開始:3

傳回值:true,說明在for裡return一個值的話相當於退出迴圈。

1)假設我們對testResult方法進行重構,抽離出for裡面的邏輯到一個單獨的方法:

public static boolean testResult() {for(int i=1; i<=5; i++) {test1(i);}return true;} public static  void  test1(int i) throws NullPointerException{System.out.println("-------------->開始:" + i);if(i == 3) {return;}System.out.println("-------------->結束:" + i);}

同樣放在main方法中。只不過testResult方法的for迴圈裡直接調的重構的方法,列印結果:

-------------->開始:1

-------------->結束:1

-------------->開始:2

-------------->結束:2

-------------->開始:3

-------------->開始:4

-------------->結束:4

-------------->開始:5

-------------->結束:5

傳回值:true

這說明,test1(i)方法用return;語句試圖走到i=3的時候中斷; 但是迴圈還是走完了。

2)不妨給for迴圈裡調用的方法一個傳回值,如下:

public static boolean testResult() {for(int i=1; i<=5; i++) {return test2(i);}return true;} public static  boolean  test2(int i) throws NullPointerException{System.out.println("-------------->開始:" + i);if(i == 3) {return true;}System.out.println("-------------->結束:" + i);return false;}

列印結果如下:

-------------->開始:1

-------------->結束:1

傳回值:false

這說明,在for裡調用一個有boolean傳回值的方法,會讓方法還沒走到i=3就斷掉,返回一個boolean值。

3)在for迴圈裡需要根據條件return一個boolean值時。for迴圈裡面的代碼若需要重構成一個方法時,應該是有傳回值的,但這個傳回值不能是boolean,我們不妨用String代替,而在for迴圈裡面用返回的String標記來判斷是否退出迴圈~~

改造如下:

public static boolean testResult() {for(int i=1; i<=5; i++) {String flag =  test3(i);if("yes".equals(flag)) {return true;}}return true;} public static  String  test3(int i) throws NullPointerException{System.out.println("-------------->開始:" + i);if(i == 3) {return "yes";}System.out.println("-------------->結束:" + i);return "no";}

列印結果:

-------------->開始:1

-------------->結束:1

-------------->開始:2

-------------->結束:2

-------------->開始:3

傳回值:true

說明達到了最初未對for迴圈裡面的代碼進行重構時的效果~

以上的小例子是我在對類似代碼進行重構時報錯的經驗小結,因為實際代碼裡,for裡面的代碼重複了好幾次,但是又因為for裡面的代碼需要根據判斷條件return一個boolean值。在重構的過程中,我先是改成test1(i),再改成test2(i), 最後改成test3(i)才該對,達到未重構時的效果。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.