个性化阅读
专注于IT技术分析

Kotlin continue跳转结构

点击下载

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

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

例如

for(..){
       //body of for above if
       if(checkCondition){
           continue
       }
//body of for below if
}

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

Kotlin继续举例

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

输出:

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

Kotlin标有继续表达

标记的是标识符的形式, 后跟@符号, 例如abc @, test @。为了使表达式成为标签, 我们只需在表达式前面放置一个标签。

Kotlin(标记为continue表达式)用于重复特定循环(标记为loop)。这是通过使用带有@符号并带有标签名称(continue @ labelname)的继续表达式来完成的。

Kotlin标为继续示例

fun main(args: Array<String>) {
    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")
    }
 }
}

输出:

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
赞(0)
未经允许不得转载:srcmini » Kotlin continue跳转结构

评论 抢沙发

评论前必须登录!