הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Loop Controls

Java provides us with two loop control structures that can help us control how we perform loop iterations from within the loop itself, they are break and continue.
A break call in a loop throws the program out of that loop. No matter what the loop condition is or if there are more iterations to perform. The next statement that will be performed after break is the first statement right after the loop. This is useful, for instance, in a search loop. Once we found the requested element in the array, we can break away from the loop (even if there are more elements in the array).

A continue call in a loop will move on to the next iteration. This is useful to filter out non-relevant inputs.

Here's a short example of using break and continue in java:

/**
* The first loop randomizes 10 numbers in a loop. If the random number
* is dividable by 7, we skip it - otherwise we print some nice comment
*/
 
public static void main(String [] args) {
  for ( int i=0; i < 10; i++ ) {
   int next = (int) (Math.random() * 50);
   if ( next % 7 == 0 ) {
    System.out.println("Skipping: " + next);
    continue;
   }

  System.out.println("Got a " + next);
}
 
/**
* The second loop randomizes 10 numbers again, only this time when
* it finds a number that is dividable by 7 it breaks completely out of the 
* loop saying bye bye
*/
public static void main(String [] args) {
  for ( int i=0; i < 10; i++ ) {
   int next = (int) (Math.random() * 50);
   if ( next % 7 == 0 ) {
    System.out.println("Bye bye" + next);
    break;
   }
}
course: