| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- /**
- * @author WanJl
- * @version 1.0
- * @title Demo01
- * @description 流程控制-分支语句-switch
- * @create 2026/7/15
- */
- public class Demo01 {
- public static void main(String[] args) {
- /*
- switch语句和if不一样,不是范围的匹配,而是针对某个值的匹配,格式:
- switch(变量){
- case 常量1:
- 代码块;
- break;
- case 常量2:
- 代码块;
- break;
- case 常量n:
- 代码块;
- break;
- default:
- 代码块;
- }
- 如果变量的值和常量1相等,就执行对应的代码块,...如果和n相等就执行对应代码块,
- 如果都不相等,就执行default中代码块
- */
- int a=3;
- switch (a){
- case 1:
- System.out.println("a=1");
- break; //break的作用,是在执行完对应的代码块后,后面的代码就不要执行了,直接跳出switch
- case 2:
- System.out.println("a=2");
- break;
- case 3:
- System.out.println("a=3");
- break;
- default:
- System.out.println("不知道");
- }
- /*
- 练习题:定义一个变量,使用switch判断1~7,分别输出 星期一~星期日
- */
- int b=3;
- switch (b) {
- case 1:
- System.out.println("星期一");
- break;
- case 2:
- System.out.println("星期二");
- break;
- case 3:
- System.out.println("星期三");
- break;
- case 4:
- System.out.println("星期四");
- break;
- case 5:
- System.out.println("星期五");
- break;
- case 6:
- System.out.println("星期六");
- break;
- case 7:
- System.out.println("星期日");
- break;
- default:
- System.out.println("不知道");
- }
- /*
- JDK17~21 增强的switch语句:可以使用任何的基本数据类型、字符串String、枚举
- */
- String day="1";
- switch (day){
- case "1","2","3","4","5" -> System.out.println("工作日");
- case "6","7" -> System.out.println("休息日");
- }
- // 使用switch匹配,匹配到了,就输出对应的语句
- switch (day){
- case "1" -> {
- System.out.println("星期一");
- System.out.println("周一");
- System.out.println("天不错");
- }
- case "2" -> System.out.println("星期二");
- case "3" -> System.out.println("星期三");
- case "4" -> System.out.println("星期四");
- case "5" -> System.out.println("星期五");
- case "6" -> System.out.println("星期六");
- case "7" -> System.out.println("星期日");
- }
- // 使用switch匹配,匹配到了,就返回对应的值,这个值,可能要拿来做其他的操作
- String dd="1";
- String s=switch (dd){
- case "1" -> "星期一";
- case "2" -> "星期二";
- case "3" -> "星期三";
- case "4" -> "星期四";
- case "5" -> "星期五";
- case "6" -> "星期六";
- case "7" -> "星期日";
- default -> "不知道";
- };
- System.out.println("今天是"+s+",天气真不错");
- }
- }
|