Any loop structure (while | for | do... while) cannot be separated from four necessary factors:
1) control variables;
2) Initial variable values;
3) variable value-added;
4) termination conditions.
For the for structure, use break or continue to exit or continue without a label:
Continue inevitably needs to increase the value of the variable. It does not need to survive the endless loop. It is a bit of the type while structure that must end with the variable value added; break jumps out directly, and the value of the control variable is the value assigned when the variable jumps out.
For the for structure with label:
Continue only adds value to the variable of the label loop; break jumps out directly.
Public Class Breaktest {
Public Static Void Main (string [] ARGs) {
String output = "" ;
Int Count;
For (Count = 1 ; Count <= 10 ; Count ++ ) {
If (Count = 5 )
Break ;
Output + = Count + " " ;
}
Output + = " \ Nbroke out of loop at Count = " + Count;
Joptionpane. showmessagedialog ( Null , Output );
System. Exit ( 0 );
}
}
Code
Import Javax. Swing. joptionpane;
Public Class Breaktest {
Public Static Void Main (string [] ARGs) {
String output = "" ;
Int Count;
For (Count = 1 ; Count <= 10 ; Count ++ ) {
If (Count = 5 )
Break ;
Output + = Count + " " ;
}
Output + = " \ Nbroke out of loop at Count = " + Count;
Joptionpane. showmessagedialog ( Null , Output );
System. Exit ( 0 );
}
}
Code
Import Javax. Swing. joptionpane;
Public Class Continuetest {
Public Static Void Main (string [] ARGs ){
String output = "" ;
Int Count;
For (Count = 1 ; Count <= 10 ; Count ++ ){
If (Count = 5 )
Continue ;
Output + = Count + " " ;
}
Output + = " \ Nused continue to skip printing 5 " ;
Joptionpane. showmessagedialog ( Null , Output );
System. Exit ( 0 );
}
}
Calculate the followingProgramResults!
Code
Public Class Labeledfor {
Public Static Void Main (string [] ARGs) {
Int I = 0 ;
Outer: // Can't have statements here
For (; True ;) { // Infinite Loop
Inner: // Can't Hava statements
For (; I < 10 ; I ++ ) {
System. Out. println ( " I = " + I );
If (I = 2 ) {
System. Out. println ("Continue");
Continue;
}
If (I = 3 ) {
System. Out. println ( " Break " );
I ++ ; // Otherwise I never gets increamented.
Break ;
}
If (I = 7 ) {
System. Out. println ( " Continue outer " );
I ++ ; // Otherwise I never gets increamented.
Continue Outer;
}
If (I = 8 ) {
System. Out. println ("Break outer");
BreakOuter;
}
For ( Int K = 0 ; K < 5 ; K ++ ) {
If (K = 3 ) {
System. Out. println ("Continue inner");
ContinueInner;
}
}
}
}
}
}