[英]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)? java 有没有办法用我创建的方法(此处为
MyMethod
) break
循环?
Or the one and only way is to make it return something and then use an if with break?或者唯一的方法是让它返回一些东西,然后使用 if 和 break?
You can use a break statement .您可以使用break 语句。
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.但是,这是可行的,但是使用具有真实条件的 while 循环可能很危险,因为您很容易陷入无限循环而无法退出它。
Your method could also return a boolean value that tells you when to stop.您的方法还可以返回告诉您何时停止的 boolean 值。 In this case, you could use the following syntax:
在这种情况下,您可以使用以下语法:
while (true) {
if( MyMethod() )
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.