Kotlin的学习日志(二)Control Flow

有关于流程控制的部分,代码如下,有任何错误的地方,请指出,谢谢大笑

/**
 * Created by Gray on 2017/5/26.
 */

/*

    流程控制
        1、if表达式
            ifTest()

        2、When代替了switch
            whenTest()
            whenTest2()

        3、for loops
            for循环可以遍历任何提供迭代器的
                for(item in collections)  print(item)
                for(item :Int in ints){}

            如果你想基于索引来迭代一个数组
                iterateTest()

        4、while loops
            while和do...while的使用还是跟java一致

        5、break和continue
            break和continue的使用也还是跟java一致

 */

fun main(args:Array<String>){
    /*ifTest(3,2)
    ifTest(2,3)*/

    /*whenTest1(1)
    whenTest1(5)
    whenTest1(15)*/

    /*whenTest2("Hello World")
    whenTest2(2)*/

    iterateTest()

}

fun ifTest(a:Int, b:Int){
   /* var max = a
    if(a<b) max = b*/

    /*var max:Int
    if(a > b){
        max = a
    }else{
        max = b
    }*/

    /*val max = if(a > b) a else b*/

    //每一块的最后一行表达式可以作为返回值
    val max = if (a > b){
        println("choose a")
        a
    }else{
        println("choose b")
        b
    }

    println(max)
}

fun whenTest1(x:Int){
   /* when(x){
        1 -> println("x == 1")
        2 -> println("x == 2")
        else -> {
            println("x is neither 1 nor 2")
        }
    }*/

    //可以使用任意的表达式作为条件
    /*when(x){
        3 - 2 -> println("x = $x")
        else -> println("x != 1")
    }*/

    //可以使用in或者!in来判断是否在范围内或者在collections中
    when(x){
        in 1..10 -> println("$x is in the range")
        !in 10..20 -> println("$x is outside the range")
        else -> print("none of the above")
    }

    //如果没有提供参数,那么条件就是true
}

fun whenTest2(x:Any) = when(x){
    is String -> println("$x is a String")
    else -> println("$x is not a String")
}

fun iterateTest(){
    var array = listOf<Int>(10,20,30)

    for (i in array.indices){
        print(array[i])
    }
    println()

    for((index, value) in array.withIndex()){
        println("The element at $index is $value")
    }

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值