Original: break[label]continue[tag] usage in Java
Note: Tags in Java must precede loops and cannot have other statements in the middle. For example: Tag:for or while or do--while;
1. Use break to exit a layer of loops (as with the break usage in C + +)
1 Public Static voidMain (String args[])2 {3 intI=0;4 while(i<100)5 { 6 if(i==10) Break;7System.out.println ("i=" +i);8i++;9 }Ten}
Attention: When break is used in a set of nested loops, it will only jump out of the innermost loop.
2. Use break to exit a multilayer loop (similar to a goto usage in C + +, skipping the outermost loop closest to the label)
1 Public Static voidMain (String args[])2 {3 outer:4 for(inti=0; i<3; i++)5 {6System.out.print ("Pass" +i+ ":");7 for(intj=0; j<100; J + +)8 {9 if(j==10)Ten Breakouter; OneSystem.out.print (j+ ""); A } -System.out.println ("This is not print"); - } theSystem.out.println ("Loops complete."); -}
Output of the program:
Pass 0:0 1 2 3 4 5 6 7 8 9 loops complete.
Use of Continue
1. Use in a one-layer loop (as with the usage in C + +)
1 Public Static voidMain (String args[])2 {3 for(inti=0; i<10; i++)4 {5System.out.print (i+ "");6 if(i%2==0)7 Continue;8System.out.println ("");9 }Ten}
Output Result:
0 1
2 3
4 5
6 7
8 9
2. Used in multi-layer loops (the first loop of the outermost loop body of the label is terminated prematurely, the next loop of the outermost loop is advanced)
1 Public Static voidMain (String args[])2 {3 outer:4 for(inti=0; i<10; i++)5 6 for(intk=0;k<10;k++)7 8 {9 for(intj=0; j<10; J + +)Ten { One if(j>i) A { - System.out.println (); - Continueouter; the } -System.out.print ("" + (i*j)); - }} - + System.out.println (); -}
0
0 1
0 2 4
0 3 6 9
0 4 8) 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
break[label]continue[tag] usage in Java