How do I break out of nested loops in Java?

前端 未结 30 2760
梦毁少年i
梦毁少年i 2020-11-21 11:51

I\'ve got a nested loop construct like this:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do somethin         


        
30条回答
  •  死守一世寂寞
    2020-11-21 12:01

    Java does not have a goto feature like there is in C++. But still, goto is a reserved keyword in Java. They might implement it in the future. For your question, the answer is that there is something called label in Java to which you can apply a continue and break statement. Find the code below:

    public static void main(String ...args) {
        outerLoop: for(int i=0;i<10;i++) {
        for(int j=10;j>0;j--) {
            System.out.println(i+" "+j);
            if(i==j) {
                System.out.println("Condition Fulfilled");
                break outerLoop;
            }
        }
        }
        System.out.println("Got out of the outer loop");
    }
    

提交回复
热议问题