简体   繁体   中英

Is it possible to break a loop using a method in java?

Example:

while(true){

    //some code

    MyMethod();

    //other code
}

Is there a way in java to break the cycle with a method I created ( MyMethod here)?

Or the one and only way is to make it return something and then use an if with break?

You can use a break statement .

while (true) {
  MyMethod();
  if( somecondition ) { // If the condition is true, then you will exit the loop
    break;
  }
}

However, this works but it might be dangerous to use a while loop with a true condition, as you could easily fall in an infinite loop and not be able to exit it.

Your method could also return a boolean value that tells you when to stop. In this case, you could use the following syntax:

while (true) {
  if( MyMethod() )
    break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM