先看下以下方法的打印结果以及返回值: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方法的里直接调的重构的方法,打印结果: -------------->开始: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)才该对,达到未重构时的效果。 以上就是php中for循环遇上return的示例代码分享的详细内容,更多请关注php中文网其它相关文章! |