09. 循环

作者: 厚土火焱 | 来源:发表于2017-11-02 23:46 被阅读116次
    For循环

    For循环可以对任何提供迭代器(iterator)的对象进行遍历。循环体是一个代码块。

    for(item:Int in ints){
        //...
    }
    

    如果要通过索引遍历一个数组或 list,可以使用 indices

    for(i in array.indices){
        print(array[i])
    }
    

    示例代码

        var items = listOf("apple", "banana", "melon", "watermelon")
        for(item in items){
            println(item)
        }
        for(index in items.indices){
            println("item at $index is ${items[index]}")
        }
    

    运行结果

    apple
    banana
    melon
    watermelon
    item at 0 is apple
    item at 1 is banana
    item at 2 is melon
    item at 3 is watermelon
    
    while和 do...while循环

    while 满足条件则执行循环体
    do...while 至少执行一次,然后条件满足再继续执行循环体

        println("---------while 使用------------")
        var x = 5
        while (x > 0){
            println(x--)
        }
        println("---------do...while 使用------------")
        var y = 5
        do{
            println(y--)
        }while (y > 0)
    

    运行结果

    ---------while 使用------------
    5
    4
    3
    2
    1
    ---------do...while 使用------------
    5
    4
    3
    2
    1
    
    返回和跳转

    Kotlin 有三种结构化跳转表达式

    • return 默认从当前函数返回
    • continue 跳出当前循环,继续下一循环
    • break 跳出当前循环,终止循环
        for(i in 1..10){
            if(i == 3) continue
            println(i)
            if(i > 5) break
        }
    

    循环结果

    1
    2
    4
    5
    6
    
    标签和continue/break的跳转

    在 kotlin 中任何表达式都可以标签来标记。标签的格式为标识符(lable)加@符号。例如:abc@、footLable@
    要给任何表达式加标签,只要加在表达式前即可。
    当 continue或break后跟随@标识符,结束当前循环,就跳转到标识符@后面的表达式位置开始执行。

    loop@ for(i in 1..100){
      for (j in 1..100){
        if (......) break @loop
      }
    }
    

    再看一个例子

    package com.cofox.kotlin
    
    /**
     * chapter01
     * @Author:  Jian Junbo
     * @Email:   junbojian@qq.com
     * @Create:  2017/11/15 10:59
     * Copyright (c) 2017 Jian Junbo All rights reserved.
     *
     * Description:
     */
    fun main(args: Array<String>) {
        for (arg in args) {
            println(arg)
        }
        for ((index, value) in args.withIndex()) {
            println("$index -> $value")
        }
        for (indexedValue in args.withIndex()) {
            println("${indexedValue.index} -> ${indexedValue.value}")
        }
    }
    

    注意第二和第三个循环的写法
    此例的输出是这样的

    a
    b
    c
    d
    ee
    f
    gg
    0 -> a
    1 -> b
    2 -> c
    3 -> d
    4 -> ee
    5 -> f
    6 -> gg
    0 -> a
    1 -> b
    2 -> c
    3 -> d
    4 -> ee
    5 -> f
    6 -> gg
    

    相关文章

      网友评论

        本文标题:09. 循环

        本文链接:https://www.haomeiwen.com/subject/javapxtx.html