Transferred from: http://lihengzkj.iteye.com/blog/1090034
It was not known that labels can be used in loops. After the recent encounter, there is still a unique use. What I mean by that is that the label can change the loop execution process in the loop. And this change is not what we used to use break alone or continue can achieve. Let's take a look at the example below.
Java code
- Outer1:
- for (int i =0;i<4;i++) {
- SYSTEM.OUT.PRINTLN ("begin to Itrate. "+i);
- For (int j =0;j<2;j++) {
- if (i==2) {
- continue outer1;
- Break
- }
- System.out.println ("Now the value of J is:" +j);
- }
- System.out.println ("******************");
- }
The result of the execution is:
Begin to Itrate. 0
Now the value of J is:0
Now the value of J is:1
******************
Begin to Itrate. 1
Now the value of J is:0
Now the value of J is:1
******************
Begin to Itrate. 2
Begin to Itrate. 3
Now the value of J is:0
Now the value of J is:1
******************
Note: When i=2, continue outer1 the program back to the beginning of the Outer1 cycle, starting the next cycle, this time the execution of the loop is i=3 instead of re-starting from i=0. Also, when using continue outer1 to jump out of the inner loop, the statement behind the outer loop will not execute. That is, at begin to Itrate. 2 There will not be a string of * numbers behind.
Contrast:
Java code
- Outer1:
- for (int i =0;i<4;i++) {
- SYSTEM.OUT.PRINTLN ("begin to Itrate. "+i);
- For (int j =0;j<2;j++) {
- if (i==2) {
- Continue outer1;
- Break ;
- }
- System.out.println ("Now the value of J is:" +j);
- }
- System.out.println ("******************");
- }
Note: If we use break directly, we just jump out of the inner loop. As a result, you can see the difference:
Begin to Itrate. 0
Now the value of J is:0
Now the value of J is:1
******************
Begin to Itrate. 1
Now the value of J is:0
Now the value of J is:1
******************
Begin to Itrate. 2
******************
Begin to Itrate. 3
Now the value of J is:0
Now the value of J is:1
******************
-----------------------------------------------------------------Split Line
Let's look at the effect of the break+ tag again.
Java code
- Outer2:
- for (int i =0;i<4;i++) {
- SYSTEM.OUT.PRINTLN ("begin to Itrate. "+i);
- For (int j =0;j<2;j++) {
- if (i==2) {
- Break Outer2;
- Break
- }
- System.out.println ("Now the value of J is:" +j);
- } System.out.println ("******************");
- }
Results:
Begin to Itrate. 0
Now the value of J is:0
Now the value of J is:1
******************
Begin to Itrate. 1
Now the value of J is:0
Now the value of J is:1
******************
Begin to Itrate. 2
Note: From the results can be seen when the i=2, the break+ tag directly to the inner and outer layers of the loop to stop. And if we use break alone, it doesn't work that way, it just jumps out of the inner loop.
Finally, the tags in Java are only suitable for use with nested loops.
The role of tags in the Java Loop (RPM)