Kotlin 条件循环控制使用

一.if条件语句

在kotlin中,if语句本身就是表达式,有返回值,kotiln并不像java一样会提高三元操作符(condition?then :else), eg: 

fun testIf(){
    var a:Int=20
    var b=30
    var max=if(a<b) a else b
    println("max")

    var min=if (a<b){
        println("Choose a:")
        a
    }else{
        println("choose b:")
        b
    }

    val x=6
    val y=10
    if (x in 1..9){
        println("x in area")
    }
}

二.when语句

在kotlin中,when语句类似于C语言的switch操作符,else 同 switch 的 default。如果其他分支都不满足条件将会求值 else 分支,如果很多分支需要用相同的方式处理,则可以把多个分支条件放在一起,用逗号分隔,eg:

fun testWhen(){
    var x=1
    when(x){
        1->{
            println("x==1")
       }
        2->{
            println("x==2")
        }
        else->{
            println("x neither 1 nor 2")
        }
    }

    when(x){
        in 0..10->{
            println("x is in 0..10 area")
        }
        else->{
            println("x is not in 0..10 area")
        }
    }


    val items= setOf("apple","pear","orange")
    when{
        "cherry" in items->{
            println("cherry is in fruits")
        }
        "apple" in items->{
            println("apple is fine too")
        }
    }

}

三.for循环

在kotlin中,for循环可以直接枚举集合中的元素,也可以按集合索引来枚举元素,for 循环可以对任何提供迭代器(iterator)的对象进行遍历,eg:

for (item in collection) print(item)

for (i in array.indices) {
    print(array[i])
}
fun testFor(){
    val items= listOf("apple","pear","orange")
    for (item in items){
        println(item)
    }

    for (index in items.indices){
        println("item at $index is ${items[index]}")
    }

    for ((index,value) in items.withIndex()){
        println("the item at $index is $value")
    }
}

四.while,do...while循环

在kotlin中,while循环和java中的while循环是一样的,也分为while和do...while,eg:

while( 布尔表达式 ) {
  //循环内容
}

do {
       //代码语句
}while(布尔表达式);
fun testWhile(){

    //while
    var x=6
    while (x>0){
        println(x--)
    }

    //do...while
    var y=8
    do {
        println(y--)
    }while (y>0)

}

五.返回和跳转

在kotlin中,和java语言类似,有三种结构化跳转方式,分别为:

1.return //认从最直接包围它的函数或者匿名函数返回

2.break //终止最直接包围它的循环

3.continue //继续下一次最直接包围它的循环

fun testJump(){
    //continue and break
    for (i in 1..12){
        if (i==5){
            continue // i为5时跳过当前循环,继续下一次循环
        }

        if (i>8){
            break // i为8时跳出循环
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值