视频链接:Java流程控制05:Switch选择结构_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV12J41137hu?p=37&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5 Java 中的
switch
选择结构是一种控制流程语句,它允许程序根据一个变量的值,从几个可能的代码路径中选择一个来执行。switch
语句的语法如下:
switch(expression){case value1:// code to be executed if expression = value1;break;case value2:// code to be executed if expression = value2;break;// you can have any number of cases;default:// code to be executed if expression doesn't match any cases;
}
switch
表达式(expression)的类型可以是 byte
、short
、int
、char
或 String
(从 Java 7 开始)。每个 case
后面的值(value1, value2, 等等)是要与表达式的值进行比较的固定值。如果有匹配,则执行对应的代码块。break
关键字用于退出 switch
语句。default
块是可选的,当没有任何 case
匹配时执行
代码举例1:
int day = 3;
switch(day){case 1:System.out.println("Monday");break;case 2:System.out.println("Tuesday");break;case 3:System.out.println("Wednesday");break;case 4:System.out.println("Thursday");break;case 5:System.out.println("Friday");break;case 6:System.out.println("Saturday");break;case 7:System.out.println("Sunday");break;default:System.out.println("Invalid day");
}
在这个例子中,switch
表达式是 day
,它会根据值(1 到 7)来选择对应的代码块执行。如果 day
的值不是 1 到 7 之间的数,则会执行 default
块中的代码。
代码举例2:
public class SwitchDemo01 {public static void main(String[] args) {char grade = 'C';switch (grade){case 'A':System.out.println("优秀");break;case 'B':System.out.println("良好");break;case 'C':System.out.println("及格");break;case 'D':System.out.println("再接再厉");break;case'E':System.out.println("挂科");break;default:System.out.println("输入错误");}}
}
从JDK7开始Switch开始支持String类型比较;
代码举例3:
public class SwitchDemo02 {public static void main(String[] args) {String name = "李四";//jdk7新特性,表达式可以是字符串;switch (name){case "张三":System.out.println("张三");break;case "李四":System.out.println("李四");break;case "王五":System.out.println("王五");break;default:System.out.println("输入错误");}}
}