ranges的使用

来源:互联网 发布:淘宝哪些店铺布料便宜 编辑:程序博客网 时间:2024/05/29 14:13

ranges的使用

(1)使用in操作符检查一个数是否在某个范围内

[plain] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /*  
  2. 判断分数是否大于等于90,小于等于100  
  3.  */  
  4. fun isGood(score: Int) {  
  5.     if(score in 90..100) //ranges是闭区间  
  6.         println("very good")  
  7.     else  
  8.         println("not so good")  
  9. }  

(2)检查索引是否越界

[plain] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /*  
  2. 检查index是否在数组arr的索引范围内  
  3.  */  
  4. fun checkIndex(index: Int, arr: Array<Int>) {  
  5.     if(index in 0..arr.lastIndex) //arr.lastIndex返回的是数组的最后一位的下标  
  6.         println("index in bounds")  
  7.     else  
  8.         println("index out of bounds")  
  9. }  

(3)遍历一个范围

[plain] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. for(i in 1..5) {  
  2.     println(i)  
  3. }  
也可以通过in运算符遍历一个集合,如下代码:
[plain] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //in运算符遍历一个字符串数组  
  2. fun testStr(arr: Array<String>) {  
  3.     for(str in arr)  
  4.         println(str)  
  5. }  

0 0