学习Switch语句。

Java流程控制

 

Switch选择结构

switch语句对流程进行控制。switch作为一个开关,当变量表达式的值对应case中的值时,执行case后面的语句后通过Break跳出switch语句。

例如对成绩等级进行判断。

 static char level;
     public static void main(String[] args) {
 
         Scanner scanner = new Scanner(System.in);
         System.out.println("请输入分数:");
 
         int score = scanner.nextInt();
         if (score <=100 && score >= 80){
             level = 'A';
        }
         else if (score <80 && score >= 70) {
             level = 'B';
        }
         else if (score <70 && score >= 60){
             level = 'C';
        }
         else level = 'D';
 
          switch (level){
              case 'A':
                  System.out.println("优秀");
                  break;
              case 'B':
                  System.out.println("良好");
                  break;
              case 'C':
                  System.out.println("及格");
                  break;
              case 'D':
                  System.out.println("不及格");
 
 
          }
    }

但是case的值是一个固定值,而不是一个范围,所以上面例子中,想要判断分数的话,需要通过if语句对分数结果进行一个等级判定,再输入到Level中,再通过Level值实现Switch语句。但其实这个例子可以不用到Switch,但还是通过这种方法学习一下。

posted @ 2021-09-29 22:58  天sir  阅读(454)  评论(0)    收藏  举报