scala模式匹配-基础使用1.1

39 阅读1分钟

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

注意:

(1) 如果把case _ 放在前面会怎么样?

image.png (2) 如果省略了case _ 并且没有匹配到的内容,会怎么样?

image.png

package matchcase
/**
 * 三大结构
 * 1. 顺序结构:
 * 2. 选择结构:
 *    (1) if, if else if else;
 *    (2) match case
 *        1.case _ 不能省略,否则会报错
 *        2.case _ 写到最后
 * 3. 循环结构:
 *    (2) for,
 *    (3) while, do...while
 */
object case01 {
  def main(args: Array[String]): Unit = {
      val code = "11"
      // var province = ""
      //
      // if(code == "42"){
      //   province = "湖北"
      // } else if(code == "11") {
      //   province = "北京"
      // } else {
      //   province = "未知"
      // }

      val province = code match {
        case "42" => "湖北"
        case "11" => "北京"
        case _ => "未知"
      }

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

小练习

输入一个1-5的数字,打印它对应的英语单词

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

    println(s"$num 对应的英语单词是: $word")

    }
}