#3 kotlin for語句及標(biāo)簽

fun main() {
    
    // outer@ 是一個標(biāo)簽 可以取任何名稱
    outer@ for (row in 1..3) {
        println("row: $row")
        for (column in 1..3) {
            if (row == 2 && column == 2) {
              println()
                continue@outer    // @outer 對應(yīng)上面的 outer@
            }
            print("$column")      
        }
        println()
    }
}

打印結(jié)構(gòu):

row: 1
123
row: 2
1
row: 3
123

即當(dāng) row == 2 && column == 2 時直接跳到了標(biāo)簽的位置。

對比一下不使用標(biāo)簽的情況

fun main() {
    
   for (row in 1..3) {
        println("row2: $row")
        for (column in 1..3) {
            if (row == 2 && column == 2) {
                println()
                continue
            }
            print("$column")      
        }
        println()
    }
}

打印結(jié)果:

row2: 1
123
row2: 2
1
3 // 此處因為沒有使用標(biāo)簽進(jìn)行跳轉(zhuǎn) 內(nèi)部循環(huán)繼續(xù)執(zhí)行完
row2: 3
123

知識點(diǎn):

  • 1..3 產(chǎn)生一個range
  • for語句中使用標(biāo)簽 labelName@ ... continue@labelName, 這個類似于C語言中的 goto 語句進(jìn)行標(biāo)記
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容