视频 视频老师的博客 更详细
1、 for 循环
println("for-in")
for(item in items){
print("$item ")
}
println("\nforEach")
items.forEach{
print("$it ")
}
println("\nforEachIndexed")
items.forEachIndexed{index, item ->
print("$index:$item ")
}
2、while 和 do-while 循环
println("\n\nwhile")
var index = 0
while(index <items.size){
print("$index:${items[index++]} ")
}
index = 0
println("\ndo-while")
do{
print("$index:${items[index++]} ")
}while(index < items.size)
3、迭代区间和数列 常用
println("\n\n遍历区间")
for (i in 1..10) {
print("$i ")
}
println("\nfor in-until")
for (i in 1 until 10) {
print("$i ")
}
println("\nfor in downTo")
for (i in 10 downTo 1) {
print("$i ")
}
println("\nfor in step")
for (i in 10 downTo 1 step 3) {
print("$i ")
}
println("\nindices")
val array = arrayOf(1,2,3)
for (i in array.indices) {
print(" "+array[i])
}
println("\nwithIndex方法")
for ((index, value) in array.withIndex()) {
print(" $index:$value ")
}
println("\n\n")
4、循环中的 break 与 continue
for (i in 1..12) {
if (i % 2 == 0) continue
for (j in 1..12) {
if (j > 5) break
print("$j ")
}
println()
}
|