Kotlin 循环控制(一)

举报
上传头像 发表于 2021/03/16 13:58:03 2021/03/16
【摘要】 For 循环for 循环可以对任何提供迭代器(iterator)的对象进行遍历,语法如下:for (item in collection) print(item)循环体可以是一个代码块:for (item: Int in ints) { // ……}如上所述,for 可以循环遍历任何提供了迭代器的对象。如果你想要通过索引遍历一个数组或者一个 list,你可以这么做:for (i in ...

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")
}

实例

对集合进行迭代:

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
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。