reset password
Author Message
lakerfan94
Posts: 143
Posted 20:20 Mar 07, 2014 |

Is there a way to break two loops simultaneously? The reason I ask is that I created a bunch of if statements within a nested for loop and I want to terminate the inner and outer loop once I've already calculated the average of the neighbors. Is there a way?

lakerfan94
Posts: 143
Posted 20:23 Mar 07, 2014 |

Never mind.

Eric Liao
Posts: 158
Posted 20:27 Mar 07, 2014 |

You can use boolean to do so.

For instance, if you have a nest loop like the following:

for ( ; ; ) {

    boolean breakOuter = false;

    for ( int i = 0; i < 10; i ++ ) {

        if ( i == 7 ) {

            breakOuter = true;

            break;

        }

        if ( breakOuter ) break;

    }

}


Or you can use label

outerloop:
    for ( ; ; ) {
      for (int i=0; i < 10; i++) {
        if ( i == 7) {
          break outerloop; // this will break outer loop since you have a "label" to indicate what is outerloop
        }
      }
    }

I would recommend boolean one more than label since you may not have label at other language besides java. And it helps you to practice the logic more than adapt the syntax.