Java, for circular relationship between the continue, break, return three

Introduction to the Theory

1, continue out of this cycle, the next one cycle
2, break out end for;
. 3, return ends the loop

Examples

Example 1:

for(int i =0;i<5;i++){
        System.out.println("当前i的值"+i);
        if(i==2){
            return;  //直接结束main()方法
        }
    }    

Example 2:

for(int i =0;i<5;i++){
        System.out.println("当前i的值"+i);
        if(i==2){
            break;  //直接结束for循环
        }
    }    

Example 3:

for(int i =0;i<5;i++){
        System.out.println("当前i的值"+i);
        if(i==2){
            continue;  //本次循环跳过,进入下一个循环
        }
    }    

Example 4

 public class ForAndIfTest {
public static void main(String[] args) {
    ArrayList<String> arrayList=new ArrayList<>();
    arrayList.add("the 1st line;");
    arrayList.add("the 2st line;");
    arrayList.add("the 3st line;");

    arrayList.add("hello world!");
    int result=indexFeatch(arrayList);
    System.out.println("result="+result);
}
public static int  indexFeatch(ArrayList<String> arrayList){
    int index=0;
    for(int i=0;i<arrayList.size();i++){
        if (arrayList.get(i).contains("hello")) {
            System.out.println("yes");
            return i;// 这里返回对应索引值,结束这个方法
        }     else
        {
//                System.out.println("not contain");
            continue;
        }
    }
    return -1;// 整个循环没有找到包含hello的字符,返回默认值-1,结束整个方法。
}
}    

Reference Link

Reproduced in: https: //www.jianshu.com/p/2069c5c66b57

Guess you like

Origin blog.csdn.net/weixin_33816946/article/details/91081201