java jumps out of the upper loop directly (multi-layer loop)

I encountered a double-layer loop in java and wanted to jump out of the double-layer loop directly. as follows:
for(int i =0;i<10;i++){
System.out.println("外部部==========="+i);
for(int j = 0;j<5;j++){
System.out.println("内部==========="+j);
if(j==3){
// jump out of the outer loop from here
}
}
}
You may have thought of break continue
But we found that using these two can only jump out of one layer of loops, but not the outermost loop. Anyone who has studied c knows that there are goto statements in C language that can jump to other positions in the program at will, while in java, goto is used as a reserved character, and its use is not recommended, because java does not advocate executing programs out of sequence during execution. The code written, however, provides tag usage in java: as follows:
                label:
for(int i =0;i<10;i++){
System.out.println("外部部==========="+i);
for(int j = 0;j<5;j++){
System.out.println("内部==========="+j);
if(j==3){
// jump out of the outer loop from here
                                   break label;
}
}
}
Add a label above the loop: as a label, we write this label where we want to jump out of the loop, and it will jump directly to the outside of the loop of this label, so that we can also jump directly to the outside of the double-layer loop. But we don't recommend doing this either. We often use a flag to handle jumping out of this double-layer loop: as follows:
for(int i =0;i<10;i++){
boolean flag = false;
System.out.println("外部部==========="+i);
for(int j = 0;j<5;j++){
System.out.println("内部==========="+j);
if(j==3){
flag = true;
break;
}
}
if(flag){
break;
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326501814&siteId=291194637