如何在不运行以下脚本的情况下退出循环

我想从第二个循环跳到第一个循环(比如休息),但休息后我不想打印fmt.Println("The value of i is", i)。算法如何?


package main


import "fmt"


func main() {

    for i := 0; i < 2; i++ {

        for j := 0; j < 4; j++ {

            if j == 2 {

                fmt.Println("Breaking out of loop")

                break

            } else {

                fmt.Println("j = ", j)

            }

        }

        fmt.Println("The value of i is", i)

    }

}



慕桂英3389331
浏览 105回答 1
1回答

慕沐林林

编辑:你编辑了你的代码,所以这里是编辑后的答案。要从内部继续外循环(打破内循环并跳过外循环的其余部分),您必须继续外循环。要使用语句解决外部循环,请continue使用标签:outer:&nbsp; &nbsp; for i := 0; i < 2; i++ {&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < 4; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if j == 2 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Breaking out of loop")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue outer&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("j = ", j)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("The value of i is", i)&nbsp; &nbsp; }这将输出(在Go Playground上尝试):j =&nbsp; 0j =&nbsp; 1Breaking out of loopj =&nbsp; 0j =&nbsp; 1Breaking out of loop原答案:break总是从最内层循环中断(更具体地说是 a或) for,因此之后外层循环将继续其下一次迭代。switchselect如果您有嵌套循环,并且您想从外部循环中断内部循环,则必须使用标签:outer:&nbsp; &nbsp; for i := 0; i < 2; i++ {&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < 4; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if j == 2 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Breaking out of loop")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break outer&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("The value of j is", j)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }这将输出(在Go Playground上尝试):The value of j is 0The value of j is 1Breaking out of loop
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go