是否可以使用 java 中的方法来打破循环?

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

示例:

while(true){

    //some code

    MyMethod();

    //other code
}

有没有办法在 java 中使用我创建的方法(此处为 MyMethodbreak 循环?

或者唯一的方法是使它成为 return 东西,然后使用带有 break 的 if?

您可以使用 break statement.

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

然而,这可行,但使用条件为真的 while 循环可能很危险,因为您很容易陷入无限循环而无法退出。

您的方法还可以 return 一个告诉您何时停止的布尔值。在这种情况下,您可以使用以下语法:

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