前言
提供一些for循环的使用demo
简单的一个数数for循环
例子1
fun main() {
for (i in 0..10){
print("i = $i ,")
}
}
i = 0 ,i = 1 ,i = 2 ,i = 3 ,i = 4 ,i = 5 ,i = 6 ,i = 7 ,i = 8 ,i = 9 ,i = 10 ,
例子2 不循环最后一位
fun main() {
for (i in 0 until 10){
print("i = $i ,")
}
}
i = 0 ,i = 1 ,i = 2 ,i = 3 ,i = 4 ,i = 5 ,i = 6 ,i = 7 ,i = 8 ,i = 9 ,
降序循环
fun main() { for (i in 10 downTo 0){ print("i = $i ,") } }
i = 10 ,i = 9 ,i = 8 ,i = 7 ,i = 6 ,i = 5 ,i = 4 ,i = 3 ,i = 2 ,i = 1 ,i = 0 ,
跳步循环
fun main() { for (i in 0 .. 10 step 2){ print("i = $i ,") } }
i = 0 ,i = 2 ,i = 4 ,i = 6 ,i = 8 ,i = 10 ,
for循环遍历时获取index
fun main() {
val list1 = mutableListOf<Data>(Data("可达鸭", 3), Data("皮卡丘", 6), Data("妙蛙种子", 9))
for ((index, itemData) in list1.withIndex()) {
println("itemData = $itemData index = $index ")
}
}
itemData = Data(name=可达鸭, id=3) index = 0
itemData = Data(name=皮卡丘, id=6) index = 1
itemData = Data(name=妙蛙种子, id=9) index = 2
双for循环跳出
fun main() {
val list1 = mutableListOf<String>("可达鸭", "皮卡丘", "妙蛙种子", "杰尼龟")
val list2 = mutableListOf<String>("皮卡丘", "小火龙", "宝石海星", "双弹瓦斯")
loop1@ for (item1 in list1) {
println("list1 = $item1")
for (item2 in list2){
println("list2 = $item2")
if (item1 == item2){
break@loop1
}
}
}
}
list1 = 可达鸭
list2 = 皮卡丘
list2 = 小火龙
list2 = 宝石海星
list2 = 双弹瓦斯
list1 = 皮卡丘
list2 = 皮卡丘