Reputation: 477
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?
Upvotes: 0
Views: 54
Reputation: 1979
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;
}
Upvotes: 1