语法结构:
1 2 3 4 5 6 7 8 9 10 11 |
|
switch语句会根据表达式的值从相匹配的case标签处开始执行,一直执行到break语句处或者是switch语句的末尾。如果表达式的值与任一case值不匹配,则进入default语句(如果存在default语句的情况)。
根据表达式值的不同可以执行许多不同的操作。switch语句中case标签在JDK1.5之前必须是整数(long类型除外)或者枚举,不能是字符串,在JDK1.7之后允许使用字符串(String)。
当布尔表达式是等值判断的情况,可以使用if-else if-else多选择结构或者switch结构,如果布尔表达式区间判断的情况,则只能使用if-else if-else多选择结构。
switch多选择结构的流程图如图所示。
测试样例:
/**
* 测试switch语句
* @author 朱鑫钰
*
*/
public class TestSwitch {
public static void main(String[]args) {
int month=(int)(1+12*Math.random());//利用函数任意赋值月份
System.out.println("月份: "+month);
switch(month) {
case 1:
System.out.println("一月份!");
break;
case 2:
System.out.println("二月份!");
break;
default:
System.out.println("其他月份");
break;
}
}
}
测试结果截图: