Java流程控制05:Switch选择结构

发布时间 2023-06-17 14:43:28作者: 斯~
  • 多选择结构还有一个实现方式就是switch case语句。
  • switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。
        switch (exception){
            case value:
                //语句
                break;//可选
            case value:
                //语句
                break;//可选
            //你可以有任意数量的case语句
            default://可选
                //语句
        }
  • switch语句中的变量类型可以是:
  1. byte、short、int或者char。
  2. Java SE7开始 switch支持字符串String类型了
  3. 同时case标签必须为字符串常量或字面量。
 1     public static void main(String[] args) {
 2         //case穿透    // switch 匹配一个具体的值
 3         char grade = 'B';
 4 
 5         switch (grade){
 6             case 'A':
 7                 System.out.println("优秀");
 8                 break;//如果没有break,此case后面还有值都会输出
 9             case 'B':
10                 System.out.println("良好");
11                 break;
12             case 'C':
13                 System.out.println("及格");
14                 break;
15             case 'D':
16                 System.out.println("挂科");
17                 break;
18             default:
19                 System.out.println("查无此人");
20         }
21     }
SwitchDemo01
 1     public static void main(String[] args) {
 2         String name = "斯图";
 3         //JDK7的新特性,表达式结果可以是字符串! ! !
 4         //字符的本质还是数字
 5 
 6         //反编译   java---class (字节码文件)----反编译(IDEA)
 7 
 8         switch (name){
 9             case "黑羽":
10                 System.out.println("黑羽");
11                 break;
12             case "空白":
13                 System.out.println("空白");
14                 break;
15             case "斯":
16                 System.out.println("斯");
17                 break;
18             case "斯图":
19                 System.out.println("斯图");
20                 break;
21             default:
22                 System.out.println("查无此人");
23         }
24     }
SwitchDemo02