In my code, I have a for loop that iterates through the code method until it encounters a for condition.
Anyway, to break out of the for loop?
So, if we look at the code below, what if we want to break out of the for loop when we get to "15"?
public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } } Outputs: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19
I tried the following to no avail:
public class Test { public static void main(String args[]) { boolean breakLoop = false; while (!breakLoop) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); if (x = 15) { breakLoop = true; } } } } }
And I tried the loop:
public class Test { public static void main(String args[]) { breakLoop: for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); if (x = 15) { break breakLoop; } } } }
The only way I can achieve what I want is to exit the for loop, I canβt substitute it for a long time, do it if, etc.
Edit:
This was provided as an example only, this is not the code I'm trying to implement. I solved the problem by putting several IF statements after each loop is initialized. Before he leaves one part of the loop due to the absence of interruptions,
java loops for-loop break
silverzx Mar 07 '13 at 15:33 2013-03-07 15:33
source share