Java Reference
In-Depth Information
System.out.println("\nLooping with No Break:");
for (int x = 0; x < 3; x++){ //outer loop (x loop)
for (int y = 0; y < 3; y++){ //inner for loop (y loop)
System.out.println("x = " + x + " and y = " + y);
}
}
6. Now add the second nested for loop section. This will include a break statement, which is exe-
cuted whenever x and y have the same value. Type the second nested for loop as follows:
System.out.println("\nBreak with No Label:");
for (int x = 0; x < 3; x++){//outer loop (x loop)
for (int y = 0; y < 3; y++){ //inner loop (y loop)
System.out.println("x = " + x + " and y = " + y);
if (x == y) { //new conditional expression
System.out.println("Break out of y loop.\n");
break; //new break statement
}
}
}
7. Finally, add a third nested for loop section. This time, include both a break statement and a label.
It will be executed under the same condition as the previous section. Type the third nested for loop
as follows:
System.out.println("\nBreak with No Label:");
outer: // new label
for (int x = 0; x < 3; x++) {// outer loop (x loop)
for (int y = 0; y < 3; y++) { // inner loop (y loop)
System.out.println("x = " + x + " and y = " + y);
if (x == y) { // same conditional expression
System.out.println("Break out of both loops.\n");
break outer; // new break statement with label
}
}
}
8. All of the preceding for loops should be between the {} of the main method. Your class body
should now look like this:
public class BreakLoop {
public static void main(String[] args) {
System.out.println("\nLooping with No Break:");
for (int x = 0; x < 3; x++) { // outer loop (x loop)
for (int y = 0; y < 3; y++) { // inner for loop (y loop)
System.out.println("x = " + x + " and y = " + y);
}
}
System.out.println("\nBreak with No Label:");
for (int x = 0; x < 3; x++) {// outer loop (x loop)
for (int y = 0; y < 3; y++) { // inner loop (y loop)
System.out.println("x = " + x + " and y = " + y);
if (x == y) { // new conditional expression
Search WWH ::




Custom Search