您的位置:首页 > 其它

switch语句

2016-01-07 22:29 309 查看
/**
* switch
*/
public static void main(String[] args) {
//1、switch如果不加break会发生case穿透现象,即无视case执行全部可执行语句,直到碰到break为止
int a = (int) (Math.random()*4+1);//a取1-5之间的整数
System.out.println("a="+a);
//穿透示例,若不加break则输出全部值,输出结果为
/**
* a=4
* 2
* 3
* 4
* 其它
*/
switch(a){//switch中表达式为int类型(可以自动转化为int类型的byte、short、char),枚举,及jdk1.7以上的字符串
case 5:
System.out.println("1");
case 4:
System.out.println("2");
case 3:
System.out.println("3");
case 2:
System.out.println("4");
default:
System.out.println("其它");
}
//合理利用穿透
switch(a){
case 5:
case 4:
case 3:
case 2:
System.out.println("4");
break;
default:
System.out.println("其它");
break;//最后一条语句,break可加可不加
}
//2、jdk1.7新特性示例
String  b = "好123";
switch (b) {   //JDK7的新特性,表达式结果可以是字符串!!!
case "搜狗":
System.out.println("搜狗");
break;
case "百度":
System.out.println("百度");
break;
default:
System.out.println("好123");
break;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: