Multiple loops can be used in Java programs to handle complex logic. But it's a hassle to jump out of the outermost loop from the inner loop. The following code is an example of a three-tier loop:
String[] arr= new string[]{"A", "B",
"C"};
for (string S:arr)
{to
(string Ss:arr) {for
(string sss:arr)
{
System.out.println (SSS);
}
}
}
If you want to jump out of the first loop from the third tier, you can do this by setting a flag, but that's a bit cumbersome. Of course, developers who have used C or C + + can think of a goto statement, as shown in the following code:
String[] arr= new string[]{"A", "B",
"C"};
for (string S:arr)
{to
(string Ss:arr) {for
(string
sss:arr)
{
System.out.println ( SSS);
goto label;
}
}
Label
Although the above code seems to be feasible, although Java also has the GOTO keyword, but this keyword is not used (the Java compiler throws an exception). However, Java also provides another kind of goto-like solution, which is break n and Continue N. where n represents the label name. Only in Java can you define a for, while, do...while three circular statements, and there can be no other statements between the label and the loop body, as the following label definition is legal:
label: //定义标签
for(int i=0;i<10;i++)
{
... ...
}
The following label definitions are not valid:
label: //定义标签
System.out.println("abcd"); //此处不能有任何Java语句
for(int i=0;i<10;i++)
{
... ...
}
The code to jump out of the multi-layer loop using break N is as follows:
Labela: For
(string S:arr)
{for (
string Ss:arr) {for (string
Sss:arr)
{
System.out.print (SSS);
Break Labela;
}
}