结构错综复杂match case带你慢慢撸

59 阅读1分钟

知识回溯

1.顺序结构

2.选择结构:

if,if else if else;

match case

case_ 不能省略,分着就会报错。

case_必须写在最后。

3.循环结构

while,

do...while

package matchcase
object case1 {
  def main(args: Array[String]): Unit = {
    val code = "11"
    /*
    val code = "41"
    var privince=""

    if (code == "42"){
      privince = "湖北"
    }else if (code == "11"){
      privince = "北京"
    }else{
      privince = "未知"
    }

     */

    val product = code match {
      case "42" =>"湖北"
      case "11" =>"北京"
      case _ =>"未知"
    }
    println(s"${code}对应省份是:$product")
  }

}
package matchcase

object case2 {
  def main(args: Array[String]): Unit = {
    //输入一个1-5的数字,打印他对应的英语单词
    val code = "1"
    val product = code match {
      case "1" =>"one"
      case "2" =>"two"
      case "3" =>"like"
      case "4" =>"apple"
      case "5" =>"sun"
      case _ =>"未知"
    }
    println(s"${code}对应的英文是:$product")
  }
}

match case 高阶匹配

1.匹配元组不同的数量

2.匹配数组特殊值

package matchcase

object case3 {
  def main(args: Array[String]): Unit = {
    val t1=(2,3)
  //  val t2=(2,3,4)
 //   val t3=(2,3,5,6)

    t1 match {
      case (a,b) => println(s"有两个元素${a},${b}")
   //   case (a,b,c) => println("有三个元素")
     // case (a,b,c,d) => println("有四个元素")
      case _=>println("未知")
    }
    val arr1 = Array(10.2)
    arr1 match {
      case Array(1,x,y) => println("数组第一个元素为1,长度为3")
      case _=>println("其他")
    }
  }
}