For循環(huán)
For循環(huán)可以對任何提供迭代器(iterator)的對象進行遍歷诫钓。循環(huán)體是一個代碼塊乞旦。
for(item:Int in ints){
//...
}
如果要通過索引遍歷一個數(shù)組或 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]}")
}
運行結(jié)果
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循環(huán)
while 滿足條件則執(zhí)行循環(huán)體
do...while 至少執(zhí)行一次,然后條件滿足再繼續(xù)執(zhí)行循環(huán)體
println("---------while 使用------------")
var x = 5
while (x > 0){
println(x--)
}
println("---------do...while 使用------------")
var y = 5
do{
println(y--)
}while (y > 0)
運行結(jié)果
---------while 使用------------
5
4
3
2
1
---------do...while 使用------------
5
4
3
2
1
返回和跳轉(zhuǎn)
Kotlin 有三種結(jié)構(gòu)化跳轉(zhuǎn)表達式
- return 默認從當前函數(shù)返回
- continue 跳出當前循環(huán)凳鬓,繼續(xù)下一循環(huán)
- break 跳出當前循環(huán)呼巴,終止循環(huán)
for(i in 1..10){
if(i == 3) continue
println(i)
if(i > 5) break
}
循環(huán)結(jié)果
1
2
4
5
6
標簽和continue/break的跳轉(zhuǎn)
在 kotlin 中任何表達式都可以標簽來標記泽腮。標簽的格式為標識符(lable)加@符號。例如:abc@衣赶、footLable@
要給任何表達式加標簽诊赊,只要加在表達式前即可。
當 continue或break后跟隨@標識符屑埋,結(jié)束當前循環(huán)豪筝,就跳轉(zhuǎn)到標識符@后面的表達式位置開始執(zhí)行。
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}")
}
}
注意第二和第三個循環(huán)的寫法
此例的輸出是這樣的
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