【问题标题】:How to break continue a nested for-loop inside a while-loop?如何在while循环中继续嵌套for循环?
【发布时间】:2015-05-27 16:38:00
【问题描述】:

我可以在嵌套的 for 循环中使用 break 以返回到外部 while 循环并在 for 循环内部使用 continue 来强制 while 循环继续运行吗?我无法将 for 循环条件放入我的 while 循环条件中,因此如果我无法在特定满足的情况下继续,while 循环可能会停止。

while(...some conditions...){
    ...print stuff
    for(...some instances are arrays, condition loop array...){
        if(...index meets conditions...){
            ...print once, some arrays might meet condition on multiple index
            break; //to prevent multiple printings
        }
    continue; //i don't want to force another while iteration if(false)
    //or is this continue for(loop) anyway?
    }
continue; //is this not essentially a while(true) loop with no return?
}

我无法将 for 循环条件放入 while 条件的原因是因为两个循环之间有更多 if 条件,例如 if(array == null) 和 if-condition x == true getArray() 如果数组是则需要调用没有传入。大部分时间条件yz 从while 循环打印,但有时条件x 满足,所以我需要for 循环。在 for-loop if(index true)) 的打印之后,我需要 while-loop 再次运行,我被困住了吗?有时这可能会发生在 while-loop 条件下,但我可以看到它不会总是如此,如果 for-loop if(index false)) 满足,我不想强​​制 while 循环,因为这可能会在运行时处理和可能会导致无限循环。

PS 我是一名初级程序员,我什至不确定这可能吗? 或有道理,如果这是一个愚蠢的问题,对不起

【问题讨论】:

  • 您可以使用标签来中断或继续循环stackoverflow.com/questions/886955/…
  • 我是一位经验丰富的程序员,使用 break 和 continue,但会保持简单。拥有boolean active = ...; while (active) { 可以提供更多控制权。
  • @usb 我同意,但没有任何其他信息,如果某个条件为真,这是跳出循环的最干净的方法之一。

标签: java arrays loops break


【解决方案1】:

你可以break带标签。

这是一个完整的例子:

https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/java/nutsandbolts/examples/BreakWithLabelDemo.java

基本上代码是这样的:

:myLabel


for (...) {
    for(...) {
        ...
        break myLabel; // Exit from both for loops
    }
}

【讨论】:

    【解决方案2】:

    continuebreak 适用于当前范围,因此如果您在 for 内,它将适用于 for

    您可以将比较结果存储在布尔变量中以检查是否要continue

    我不是breakcontinue 的忠实粉丝,我认为这会妨碍可读性。您可以使用不同的代码结构来实现相同的行为。

    【讨论】:

      【解决方案3】:

      你可以这样命名你的循环:

      namedLoop: for(...) {
          // access your namedloop
          break namedLoop;
      }
      

      【讨论】:

      • 函数应该替换所有标签转到的情况。意大利面条代码是维护的噩梦。
      • 我并不是说这是最好的方法,它肯定会损害可读性和维护性,但根据设计代码的复杂性,它只是更简单一点(打破完成的排序例如排序例程中的数组)
      • @Kevin 我可以在嵌套的 for(loop) 中以 continue namedLoop; 的身份执行此操作吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 2023-03-02
      • 2020-10-09
      相关资源
      最近更新 更多