ranges的使用

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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值