java中Switch语句的用法

 switch的常见用法如下:

public String method(String variable){
	switch (variable){
		case "11":
			System.out.println("111");
			break;
		case "22":
			System.out.println("222");
			break;
		default:
			System.out.println("def");
	}
}

注意:

1、switch后的变量可以是byteshortintcharString类型;

2、case之后的值必须和switch变量的类型一致

3、default是在没有 case 语句的值和变量值相等的时候执行。

break的常见应用情况:

1、case中两个值进行一样的操作

//传值为B或C执行代码一样
public String method(char variable){
	switch(grade)
	{
	 case 'A' :
		System.out.println("优秀"); 
		break;
	 case 'B' :
	 case 'C' :
		System.out.println("良好");
		break;
	 case 'D' :
		System.out.println("及格");
		break;
	 case 'F' :
		System.out.println("你需要再努力努力");
		break;
	 default :
		System.out.println("未知等级");
	}
}

2、case语句没有break时,匹配成功后,从当前 case 开始,后续所有 case 的值都会输出。

//传值为3
public String method(int variable){
	switch(i){
		case 9:
			System.out.println("9");
		case 3:
			System.out.println("3");
		case 6:
			System.out.println("6");
		default:
			System.out.println("def");
	}
}

输出为:

3、如果当前匹配成功的 case 语句块没有 break 语句,则从当前 case 开始,后续所有 case 的值都会输出,如果后续的 case 语句块有 break 语句则会跳出判断。

//传值为3
public String method(int variable){
	switch(i){
		case 9:
			System.out.println("9");
		case 3:
			System.out.println("3");
		case 6:
			System.out.println("6");
			break;
		default:
			System.out.println("def");
	}
}

 输出为:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值