有关于流程控制的部分,代码如下,有任何错误的地方,请指出,谢谢
/**
* 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")
}
}