先看下以下方法的打印結果以及返回值:
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)才該對,達到未重構時的效果。
希望各位同仁們遇到for循環裏面需要return;或return true/false;時,一定要謹慎哈~