Kotlin for循环

1.for-in循环

var desc = ""

for (item in listData){
desc = "${desc}:${item},"      
}
//(2)indices
for (i in listData.indices) {
val item = listData[i]
desc = "${desc}:${item},"  
}

2.迭代

var desc = ""
val iterator = listData.iterator()
while (iterator.hasNext()) {
val item = iterator.next()
desc = "${desc}:${item},"      
}
  1. forEach
var desc = ""
//forEach内部it代表每一条
listData.forEach { desc = "${desc}:${it},"   }

4.do while

var i:Int = 0
do {
//doSomething
} while (i < listData.size)

5.其他条件循环

for (i in 11 until 66) { ... }//包括11但是不包括66
for (i in 23..89 step 4) { ... }//每次递增1 改为递增4
for (i in 50 downTo 7) { ... } //downTo 标识递减

6.continue break

fun main() {

    val poem2Array: Array = arrayOf(
        "朝辞白帝彩云间", null, "千里江陵܉一日还", "",
        "两岸猿声啼不住", " ", "轻舟已过万重山", "送孟浩然之广陵"
    )
    var poem: String = ""
    var pos: Int = -1
    var count: Int = 0
    while (pos <= poem2Array.size) {
        pos++
        if (poem2Array[pos].isNullOrBlank())
            continue
        if (count % 2 == 0) {
            poem = "$poem${poem2Array[pos]},\n"
        } else {
            poem = "$poem${poem2Array[pos]}。\n"
        }
        count++
        if (count == 4)
            break
    }

    println(poem)
}
image.png

你可能感兴趣的:(Kotlin for循环)