Kotlin教程:continue语句用于重复循环

2023年 7月 12日 38.2k 0

Kotlin的continue语句用于重复循环。 它继续当前程序流并在指定条件下跳过剩余代码。

嵌套循环中的continue语句仅影响内部循环。

示例

for(..){  
       // for中的if语句上部分主体
       if(checkCondition){  
           continue  
       }  
    //for中的if语句下部分主体
}

Kotlin

在上面的例子中,for循环重复循环,if条件执行继续。 continue语句重复循环而不执行if条件的下面代码。

Kotlin continue示例

fun main(args: Array) {
    for (i in 1..3) {
        println("i = $i")
        if (j == 2) {
            continue
        }
        println("this is below if")
    }
}

Kotlin

执行上面示例代码,得到以下结果 -

i = 1
this is below if
i = 2
i = 3
this is below if

Kotlin标记continue表达式

标记是标识符的形式,后跟@符号,例如abc@test@。 要将表达式作为标签,只需在表达式前面添加一个标签。

标记为continue表达式,在Kotlin中用于重复特定的循环(标记的循环)。 通过使用带有@符号后跟标签名称的continue表达式(continue@labelname)来完成的。

Kotlin标记为continue的示例

fun main(args: Array) {
    labelname@ for (i in 1..3) {
        for (j in 1..3) {
            println("i = $i and j = $j")
            if (i == 2) {
                continue@labelname
            }
            println("this is below if")
        }
    }
}

Kotlin

执行上面示例代码,得到以下结果 -

i = 1 and j = 1
this is below if
i = 1 and j = 2
this is below if
i = 1 and j = 3
this is below if
i = 2 and j = 1
i = 3 and j = 1
this is below if
i = 3 and j = 2
this is below if
i = 3 and j = 3
this is below if

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-continue-structure.html

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论