先看下以下方法的列印結果以及傳回值:
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)才該對,達到未重構時的效果。