how to break two loop in java
import java.io.IOException;
/**
* How to break from nested loop in Java. You can use labeled
* statement with break statement to break from nested loop.
*
* @author WINDOWS 8
*/
public class BreakingFromNestedLoop{
public static void main(String args[]) throws IOException {
// this is our outer loop
outer: for (int i = 0; i < 4; i++) {
// this is the inner loop
for (int j = 0; j < 4; j++) {
// condition to break from nested loop
if (i * j > 5) {
System.out.println("Breaking from nested loop");
break outer;
}
System.out.println(i + " " + j);
}
}
System.out.println("exited");
// better way is to encapsulate nested loop in a method
// and use return to break from outer loop
breakFromNestedLoop();
}
/**
* You can use return statement to return at any point from a method.
* This will help you to break from nested loop as well
*/
public static void breakFromNestedLoop(){
for(int i=0; i<6; i++){
for(int j=0; j<3; j++){
int product = i*j;
if(product > 4){
System.out.println("breaking from nested loop using return");
return;
}
}
}
System.out.println("Done");
}
}
Output
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
Breaking from nested loop
exited
breaking from nested loop using return
Also in Java:
- how to reverse a list in java
- how to ask user for his location in android
- difference between compile and execute in java
- deleting elements of an array in java
- count word in string no matter the delimiter java
- javafx detect collision
- spring iterate
- how to remove all whitespace from string java
- double parse jtextfield
- java 8 findany on null list
- java prev permutation
- one line if statement java
- writing to a text file java
- how to remove components from a JFRame java
- java regex replace all characters before
- java null pointer exception
- processing sound library
- how to create gravity in java
- how to play an audio in java
- fibonacci sequence in java recursion
- java fx display simple rectangle
- how to create a thread local variable in java
- islowercase java
- make a commet in java