栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

六、Kotlin循环控制

Java 更新时间:发布时间: 百科书网 趣学号

视频 视频老师的博客 更详细

1、 for 循环
//for item in elements  elements可以是数组、集合
//1.1 for-in
println("for-in")
for(item in items){
    print("$item ")
}
//1.2 forEach
println("nforEach")
items.forEach{
    print("$it ")
}
//1.3 forEachIndexed
println("nforEachIndexed")
items.forEachIndexed{index, item ->
    print("$index:$item   ")
}
2、while 和 do-while 循环
//2.while 和 do-while
//2.1 while 先判断再循环
println("nnwhile")
var index = 0
while(index  
3、迭代区间和数列 常用 
//遍历区间,注意Kotlin的区间的包含或是闭合的
println("nn遍历区间")
for (i in 1..10) { //[1,10]
    print("$i ")
}
//for in-until 前闭后开
println("nfor in-until")
for (i in 1 until 10) { //[1,10)
    print("$i ")
}
//for in downTo
println("nfor in downTo")
for (i in 10 downTo 1) { //downTo 倒序遍历
    print("$i ")
}
//for in downTo step
println("nfor in step")
for (i in 10 downTo 1 step 3) { //倒序 步长为3
    print("$i ")
}
//遍历数组时或list
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("nn")
4、循环中的 break 与 continue
//4.break continue
for (i in 1..12) {
    if (i % 2 == 0) continue // 如果 i 能整除于 2,跳出本次循环,进入下一个循环
    for (j in 1..12) {
        if (j > 5) break // 如果 j 小于 10 ,终止循环。
        print("$j ")
    }
    println()
}
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/294932.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号