分支结构:switch选择结构
语法格式:
switch(表达式){
case 常量值1:
语句块1;
【break;】
case 常量值2:
语句块2;
【break;】
。。。
【default:
语句块n+1;
【break;】
】
}
执行过程:
(1)入口
①当switch(表达式)的值与case后面的某个常量值匹配,就从这个case进入;
②当switch(表达式)的值与case后面的所有常量值都不匹配,寻找default分支进入;不管default在哪里
(2)一旦从“入口”进入switch,就会顺序往下执行,直到遇到“出口”,即可能发生贯穿
(3)出口
①自然出口:遇到了switch的结束}
②中断出口:遇到了break等
注意:
(1)switch(表达式)的值的类型,只能是:4种基本数据类型(byte,short,int,char),两种引用数据类型(JDK1.5之后枚举、JDK1.7之后String)
(2)case后面必须是常量值,而且不能重复
**public class SwitchDemo01 {
public static void main(String[] args) {
//定义指定的星期
int weekday = 5;
//switch语句实现选择
switch(weekday) {
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("你的数字有误");
break;
}
}
}**
case的穿透性
在switch语句中,如果case的后面不写break,将出现穿透现象,也就是一旦匹配成功,不会在判断下一个case的值,直接向后运行,直到遇到break或者整个switch语句结束,switch语句执行终止。
根据指定的月份输出对应季节(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("你输入的月份有误");
}
}
}
根据指定的月份输出对应季节(switch语句)
public class SwitchTest02 {
public static void main(String[] args) {
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;
}
}
}