模式匹配-基础使用

39 阅读2分钟

我们今天接到一个开发任务,就是根据身份证号码,输出这个人的籍贯。例如:42表示湖北,33表示浙江,11表示北京,31表示上海。

object score1 {
  def main(args: Array[String]): Unit = {
    val code ="11"
    val province =code match {
      case "42" => "湖北"
      case "11" => "北京"
      case _=> "未知"

    }
    println(s"${code}对应的省份是:${province}")
  }

}

三大结构‌

  • 顺序结构‌
  • ‌选择结构‌
  • if, if else if else
  • match case
  • case _: 不可省略,否则匹配失败会报错
  • case _: 必须写在最后
  • ‌循环结构‌
  • for
  • while, do...while
object score2 {
  /**
   * 三大结构‌
   * 顺序结构‌
   * ‌选择结构‌
   * if, if else if else
   * match case
   * case _: 不可省略,否则匹配失败会报错
   * case _: 必须写在最后
   * ‌循环结构‌
   * for
   * while, do...while
   *
   *
    */


 def main(args: Array[String]): Unit = {
   //输入一个1~5的数字,打印它对应的英语单词
   val num =1
   val word =num match {
     case "1" => "one"
     case "2"=>"two"
     case "3"=>"three"
     case "4"=>"four"
     case "5"=>"five"

   }
   println(s"${num}对应的英文是:${word}")
 }
}

match case 高阶匹配

* 1.匹配元组不同的数组

object score2 {
  /**
   *
   * match case 高阶匹配
   * 1.匹配元组不同的数组
    */


 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 _=>println("未知")
   }

 }
}

* 2.匹配数组的特殊值

object score2 {
  /**
   *
   * match case 高阶匹配
   * 1.匹配元组不同的数组
   * 2.匹配数组的特殊值
    */


 def main(args: Array[String]): Unit = {
//元组
       val t1 = (1,2)
       t1 match {
         case (a,b) => println(s"有二个元素${a}, ${b}")
         case _ => println("未知")
       }
       val arr1 = Array(10,2)
       arr1 match {
         case Array(1,x,y) => println("数组,第一个元素是1,长度为3")
         case Array(10,x) => println("数组,第一个元素是10,长度为2")
         case _ => println("其他")
       }
     }


}

OIP-C.jpg

  • 完结撒花 !!!!!!!!!!
  • 制作不易 希望·一键三连 在此感谢关注的粉丝宝宝
  • 新来的宝宝可以关注下主播哟!!!!!