1.if ...else
eg:
var score = 96
if (score > 90){
print("优秀")
}else{
print("非优秀")
}
2.if...else if...else 语句
eg:
var score = 96
if (score > 90){
print("优秀")
}else if(score > 80){
print("良好")
} else if(score > 60){
print("及格")
}else{
print("不及格")
}
3.match
相当于 Java中的switch
ps: match 中用 case _ 代表如果都匹配不上,默认返回的值,_ 也可以 理解为匹配所有值。相当于 Java中switch 的 default
如果 不写 默认值 case _ 则Scala默认 最后一个 case 为默认值
var score = 61
score match {
case 69 => {
print("69")
}
case 65 =>{
print("65")
}
case _ => print("none")
}
eg2: 使用 match 匹配变量的 数据类型
val list = List(1,2,3.4,"spark","hive")
for(i <- list){
val rs = i match {
case i:Int =>"i is a Int" // 判断i 数据类型 是否为 Int
case i:Double => "i is a double"
case i:String => "i is string , "+i
case _ => "i is unknown type"
}
println(rs)
}
输出:
eg3: 使用 match 结合 guard 守卫判断
val list =List(1,2,3,4,5,6)
for(ele <- list){
val rs = ele match {
case _ if(ele %2 == 0) => {ele+" is a even."} //添加guard 判断
case _ => {ele +"is a odd."}
}
println(rs)
}
输出:
eg4: 如果 不写 默认值 case _ 则Scala默认 最后一个 case 为默认值
case class People(val name:String, val age:Int){ } val saveList = new ListBuffer[String] val peopleList = List(People("zs",1),People("ls",2),People("ww",9999)) for(ele <- peopleList){ val result = ele match { case People("zs",1) => {"this is ww 33"} case People("zs",99) => {"this is 张三, 99岁了"} case People(pname,page) =>{"this people's name is "+pname+", and page is "+page} } saveList.append(result) } saveList.foreach(println(_))
输出:
4.for 循环中的if 判断
for (i <- 1 to 10
if i%2 == 0){
print(i)
}
5.if 可以被赋值
eg:
val x = 6
val a = if(x > 0) 1 else 0
则a 会被赋值为 1