Java基础—switch-case

形式如下:
switch(表达式)
{
case 取值1:
执行语句;
break;
case 取值2:
执行语句;
break;
…...
default:
执行语句;
break;
}
取值必须是int型的,或者是能够自动进行饮试转换成int型的表达式。也就是说A部分可以是byte/short/char/int型的。
其次要强调的是该程序中B部分的值必须是单个byte/short/char/int型的值,或者是final型的变量,都需要初始化,或者枚举类型。
java7以后可以支持switch(String)


例子1:

public class Test001 {

	public static void main(String[] args) {
		byte a = 11;
		switch(a){// C
		case 11 : 
			System.out.println(" 11 "); 
			break;
		case 2 : 
			System.out.println(" 11 "); 
			break;// D
		}
	}
}

该代码正确吗?答案是否定的。虽然在 C 处是合法的也即是byte型的a值可以出现在switch中,但是 D处的语句也即是第二个case后的值是225大小超过了byte的范围,所以是错误的。再就是case后的值不能出现重复。因此在使用中要注意。


再就是在使用switch-case中最容易忽视的就是忘记在每个case后处理完后忘记写上break;语句。那它带来的后果是什么呢

例子2:

public class Test002 {

	public static void main(String[] args) {
		byte a = 2;
		switch (a) {
		case 1:
			System.out.println(" A ");
		case 2:
			System.out.println(" B ");
		case 3:
			System.out.println(" C ");
		case 4:
			System.out.println(" D ");
		default:
			System.out.println(" default ");
		}
	}
}
=========输出结果为:
 B 
 C 
 D 
 default 

--------------------------

例子3:

public class Test003 {

	public static void main(String[] args) {
		int x = 2;
		switch (x)// byte,short,int,char.
		{
		default:
			System.out.println("d");
			// break;
		case 4:
			System.out.println("a");
			// break;
		case 1:
			System.out.println("b");
			break;
		case 3:
			System.out.println("c");
			break;

		}

	}
}
=========输出结果为:
 d
 a 
 b 

--------------------------

例子4:
public class Test004 {

	public static void main(String[] args) {
		int month = 13;

		switch (month) {
		case 3:
		case 4:
		case 5:
			System.out.println(month + "月对应的是春季");
			break;
		case 6:
		case 7:
		case 8:
			System.out.println(month + "月对应的是夏季");
			break;
		case 9:
		case 10:
		case 11:
			System.out.println(month + "月对应的是秋季");
			break;
		case 12:
		case 1:
		case 2:
			System.out.println(month + "月对应的是冬季");
			break;
		default:
			System.out.println(month + "月没有对应的季节");
			// break; 最后一个break可以省略
		}

	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值