在switch语句中,如果case的后面不写break,将出现穿透现象,也就是一旦匹配成功,不会在判断下一个case的值,直接向后运行,直到遇到break或者整个switch语句结束,switch语句执行终止。
Switch 表达式也是作为预览语言功能的第一个语言改动被引入Java12 中,开始支持如下写法:
switch(month) {
case 3,4,5 -> System.out.println("春季");
case 6,7,8 -> System.out.println("夏季");
case 9,10,11 -> System.out.println("秋季");
case 12,1,2 -> System.out.println("冬季");
default->System.out.println("月份输入有误!");
};
练习:根据指定的月份输出对应季节(switch语句)
/*
* 需求:指定一个月份,输出该月份对应的季节。
* 一年有四季
* 3,4,5 春季
* 6,7,8 夏季
* 9,10,11 秋季
* 12,1,2 冬季
*
* 分析:
* A:指定一个月份
* B:判断该月份是几月,根据月份输出对应的季节
* if
* switch
*/
public class SwitchTest02 {
public static void main(String[] args) {
//指定一个月份
int month = 5;
/*
switch(month) {
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;
case 8:
System.out.println("夏季");
break;
case 9:
System.out.println("秋季");
break;
case 10:
System.out.println("秋季");
break;
case 11:
System.out.println("秋季");
break;
case 12:
System.out.println("冬季");
break;
default:
System.out.println("你输入的月份有误");
break;
}
*/
// 改进版
switch(month) {
case 1:
case 2:
case 12:
System.out.println("冬季");
break;
case 3:
case 4:
case 5:
System.out.println("春季");
break;
case 6:
case 7:
case 8:
System.out.println("夏季");
break;
case 9:
case 10:
case 11:
System.out.println("秋季");
break;
default:
System.out.println("你输入的月份有误");
break;
}
}
}
练习:根据指定的月份输出对应季节(if语句)
/*
* 需求:定义一个月份,输出该月份对应的季节。
* 一年有四季
* 3,4,5 春季
* 6,7,8 夏季
* 9,10,11 秋季
* 12,1,2 冬季
*
* 分析:
* A:指定一个月份
* B:判断该月份是几月,根据月份输出对应的季节
* if
* switch
*/
public class SwitchTest01 {
public static void main(String[] args) {
//指定一个月份
int month = 5;
/*
if (month == 1) {
System.out.println("冬季");
} else if (month == 2) {
System.out.println("冬季");
} else if (month == 3) {
System.out.println("春季");
} else if (month == 4) {
System.out.println("春季");
} else if (month == 5) {
System.out.println("春季");
} else if (month == 6) {
System.out.println("夏季");
} else if (month == 7) {
System.out.println("夏季");
} else if (month == 8) {
System.out.println("夏季");
} else if (month == 9) {
System.out.println("秋季");
} else if (month == 10) {
System.out.println("秋季");
} else if (month == 11) {
System.out.println("秋季");
} else if (mouth == 12) {
System.out.println("冬季");
} else {
System.out.println("你输入的月份有误");
}
*/
// 改进版
if ((month == 1) || (month == 2) || (month == 12)) {
System.out.println("冬季");
} else if ((month == 3) || (month == 4) || (month == 5)) {
System.out.println("春季");
} else if ((month == 6) || (month == 7) || (month == 8)) {
System.out.println("夏季");
} else if ((month == 9) || (month == 10) || (month == 11)) {
System.out.println("秋季");
} else {
System.out.println("你输入的月份有误");
}
}
}