范围Range


数字范围

关键符号

.. !in in

可以看出 可以用数字和字符作为访问

  • 普通使用
 for (num in 1..10) {
        println("The num is $num")
    }
 for(ch in '1'..'a'){
        println("The char is $ch")
    }

The num is 1
The num is 2
The num is 3
The num is 4
The num is 5
The num is 6
The num is 7
The num is 8
The num is 9
The num is 10
The char is 1
The char is 2
The char is 3
The char is 4
The char is 5
The char is 6
The char is 7
The char is 8
The char is 9
The char is :
The char is ;
The char is <
The char is =
The char is >
The char is ?
The char is @
The char is A
The char is B
The char is C
The char is D
The char is E
The char is F
The char is G
The char is H
The char is I
The char is J
The char is K
The char is L
The char is M
The char is N
The char is O
The char is P
The char is Q
The char is R
The char is S
The char is T
The char is U
The char is V
The char is W
The char is X
The char is Y
The char is Z
The char is [
The char is \
The char is ]
The char is ^
The char is _
The char is `
The char is a

Process finished with exit code 0
  • 降序排序

刚才我们看见,这是打印都是升序范围,那降序怎么做呢,受上面的启发,我们想这样

fun BaseMain() {
    for (num in 10..1) {
        println("The num is $num")
    }
}

我们是期待倒序打印的,但是我们会发现,没有打印任何东西 。。。很尴尬,正确姿势如下

fun BaseMain() {
    for (num in 10 downTo 1) println("The num is $num")
}
/**
The num is 10
The num is 9
The num is 8
The num is 7
The num is 6
The num is 5
The num is 4
The num is 3
The num is 2
The num is 1
*/
  • 递增间隔step

上面的例子是都递增1 如果你想递增其他数量,请使用step

 for (num in 10 downTo 1 step 3) println("The num is $num")
 /**
The num is 10
The num is 7
The num is 4
The num is 1
 */
  • 不使用最后一个元素

使用util,但是如果是降序就不知道怎么用了

for (letter in 1 until 10 step 3) println("The num is $letter")
/**
The num is 1
The num is 4
The num is 7
*/

results matching ""

    No results matching ""