内建控制-if语句

38 阅读1分钟

(一)if语句的格式和执行流程

if(布尔表达式 1){  
   // 如果布尔表达式 1 为 true 则执行该语句块  
}else if(布尔表达式 2){  
   // 如果布尔表达式 2 为 true 则执行该语句块  
}else if(布尔表达式 3){  
   // 如果布尔表达式 3 为 true 则执行该语句块  
}else {  
   // 如果以上条件都为 false 执行该语句块  
}

(二)案例一判断是否成年

object Base07 {
  def main(args: Array[String]): Unit ={
    //1. 获取用户输入的数字
    // 2.判断
    // 3.输出结果

    print("请输入年龄:")
    val age = scala.io.StdIn.readInt()
    if(age > 18){
      println("成年")
    }else{
      println("未成年")
    }
  }
}

( 三)案例二比较正方形和长方形面积大小

object Base08 {
  def main(args: Array[String]): Unit ={
    print("请输入正方形边长:")
    val a =scala.io.StdIn.readInt()
    print("请输入长方形长:")
    val b =scala.io.StdIn.readInt()
    print("请输入长方形宽:")
    val c =scala.io.StdIn.readInt()
    if(b*c > a*a){
      println("长方形面积大")
    }else if (b*c < a*a){
      println("正方形面积大")
    }else{
      println("面积一样大")
    }
  }
}

(四)案例三输入分数输出等级

object Base09 {
  def main(args: Array[String]): Unit ={
    print("输入正整数分数")
    val score = scala.io.StdIn.readInt()
    if (90 <= score && score<= 100){
      println("A等")
    }else if (80 <= score && score<= 89 ){
      println("B等")
    }else if (70 <= score && score<= 79) {
      println("C等")
    } else if (60 <= score && score<= 69) {
      println("D等")
    } else if (0 <= score && score<= 59) {
      println("E等")
    }
//    else {
//      println("输入有误")
//    }
  }
}

**最后一个else在语法上是可以省略的