/**
学习for循环的使用
**/
object Demo05 {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
val a1=Array(1,2,3,4) //> a1 : Array[Int] = Array(1, 2, 3, 4)
for(i<-a1){
println(i) //> 1
//| 2
//| 3
//| 4
}
//--通过for,打印1~10的数字
for(i<-1 to 10)println(i) //> 1
//| 2
//| 3
//| 4
//| 5
//| 6
//| 7
//| 8
//| 9
//| 10
//--用scala的for循环,打印99乘法表
//--1*1=1
//--1*2=2 2*2=4
//--1*3=3 2*3=6 3*3=9
for(a<-1 to 9){
for(b<-1 to a){
print(b+"*"+a+"="+b*a+"\t")
}
println
} //> 1*1=1
//| 1*2=2 2*2=4
//| 1*3=3 2*3=6 3*3=9
//| 1*4=4 2*4=8 3*4=12 4*4=16
//| 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
//| 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
//| 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
//| 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
//| 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
//|
//--scala的for循环非常强大,可以写多种条件语句
//--注意:for(里的赋值,比如是常量val){}
for(a<-1 to 9;b<-1 to a;val sep=if(a==b)"\r\n" else "\t"){
print(s"$b*$a=${b*a}$sep") //> 1*1=1
//| 1*2=2 2*2=4
//| 1*3=3 2*3=6 3*3=9
//| 1*4=4 2*4=8 3*4=12 4*4=16
//| 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
//| 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
//| 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
//| 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
//| 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
}
for(i<-1 to 10;if i>6;if i%2==0)println(i) //> 8
//| 10
for(i<-1 to 10;if i>6&&i%2==0)println(i) //> 8
//| 10
//--声明一个map
val m1=Map("tom"->23,"rose"->30,"jim"->35) //> m1 : scala.collection.immutable.Map[String,Int] = Map(tom -> 23, rose -> 30
//| , jim -> 35)
for(i<-m1){
println(i) //> (tom,23)
//| (rose,30)
//| (jim,35)
}
//--掌握这种遍历map的方式
for((m,n)<-m1){
println(m) //> tom
//| rose
//| jim
}
//--学习 for yield表达式的作用:
//--操作某一个集合类型,并返回对应的集合类型
//--scala的集合是一个大的概念,涵盖了:
//--Array,List,Set,Map,Range,tuple
val a2=Array(1,2,3,4) //> a2 : Array[Int] = Array(1, 2, 3, 4)
//--现在要实现:操作a2,每个元素*2并返回到一个新数组
val a3=for(i<-a2)yield{i*2} //> a3 : Array[Int] = Array(2, 4, 6, 8)
val l2=List(1,2,3,4) //> l2 : List[Int] = List(1, 2, 3, 4)
val l3=for(i<-l2) yield{i*3} //> l3 : List[Int] = List(3, 6, 9, 12)
import util.control.Breaks._
/**
知识点
1.scala的异常捕获机制同java,不同在于catch里通过case语法来匹配异常=>函数的值
**/
object Demo06 {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
try{
throw new RuntimeException
}catch{
case t:NullPointerException=>{
println("Null Error")
}
case t:Exception=>{
println("other Error")
}
}finally{
println("end")
} //> other Error
//| end
val s1="world" //> s1 : String = world
//--scala的match机制类似于java的switch语句
//--scala的match是有返回值的,可以接收
val r1=s1 match{
case "hello"=>{
println(1)
200
}
case "world"=>{
println(2)
100
}
} //> 2
//| r1 : Int = 100
breakable(
for(i<-1 to 10){
if(i>8){
break
}else{
println(i)
}
}) //> 1
//| 2
//| 3
//| 4
//| 5
//| 6
//| 7
//| 8
//--如果breakable在循环外,break是跳出循环的效果
//--如果在循环内,break是continue效果
for(i<-1 to 10){
breakable(
if(i==8){
break
}else{
println(i)
}
) //> 1
//| 2
//| 3
//| 4
//| 5
//| 6
//| 7
//| 9
//| 10
}
}
```