Kotlin學習筆記4——循環控制

Kotlin學習筆記4——循環控制

前言

上一篇,我們學習了Kotlin條件控制,今天繼續來學習Kotlin中循環控制。

for 循環

for 循環可以對任何提供迭代器(iterator)的對象進行遍歷,語法如下:

for (item in collection) print(item)

循環體可以是一個代碼塊:

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

如上所述,for 可以循環遍歷任何提供了迭代器的對象。
如果你想要通過索引遍歷一個數組或者一個 list,你可以這麼做:

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

注意這種"在區間上遍歷"會編譯成優化的實現而不會創建額外對象。
或者你可以用庫函數 withIndex:

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

如果你需要按反序遍歷整數可以使用標準庫中的 downTo() 函數:

for (i in 4 downTo 1) print(i) // 打印結果爲: "4321"

也支持指定步長:

for (i in 1..4 step 2) print(i) // 打印結果爲: "13"

for (i in 4 downTo 1 step 2) print(i) // 打印結果爲: "42"

如果循環中不要最後一個範圍區間的值可以使用 until 函數:

for (i in 1 until 10) { // i in [1, 10), 不包含 10
     println(i)
}

接下來看個實例:

fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
    for (item in items) {
        println(item)
    }

    for (index in items.indices) {
        println("item at $index is ${items[index]}")
    }
}

輸出結果:

apple
banana
kiwi
item at 0 is apple
item at 1 is banana
item at 2 is kiwi

while 與 do…while 循環

while是最基本的循環,它的結構爲:

while( 布爾表達式 ) {
  //循環內容
}

do…while 循環 對於 while 語句而言,如果不滿足條件,則不能進入循環。但有時候我們需要即使不滿足條件,也至少執行一次。

do…while 循環和 while 循環相似,不同的是,do…while 循環至少會執行一次。

do {
       //代碼語句
}while(布爾表達式)

接下來看個實例:

fun main(args: Array<String>) {
    println("----while 使用-----")
    var x = 5
    while (x > 0) {
        println( x--)
    }
    println("----do...while 使用-----")
    var y = 5
    do {
        println(y--)
    } while(y>0)
}

輸出結果:

5
4
3
2
1
----do...while 使用-----
5
4
3
2
1

尾巴

今天的學習筆記就先到這裏了,下一篇我們將學習Kotlin中的返回與跳轉
老規矩,喜歡我的文章,歡迎素質三連:點贊,評論,關注,謝謝大家!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章