DAY4-基本switch语句

  switch语句用于选择判断。
  当判断条件较多时,用if或嵌套的if语句会降低程序的可读性,这时可用switch语句实现多重选择判断。
switch语句的语法形式:

switch(表达式)

{

catch 常量1;

语句组1;

case 常量2;

语句组2;

.....

case 常量n;

语句组n;

default;

语句组n+1;

}

  switch语句的执行过程是,先计算“表达式”的值,表达式的值与哪一个“常量”相同(匹配)则转到哪个“语句组”并执行该“语句组”,执行之后,再接着执行下面的语句组,直到之后的所有语句组执行完毕,整个switch语句结束。

break的使用:如果想使某一情况下只执行某一语句组,可以在每一语句组后加上“break”语句。“break”语句可以提前结束switch的执行,后面的语句组都不被执行了。

switch(表达式)
{
  case 常量1:
    语句组1;break;
  case 常量2:
    语句组2;break;
    ……
  case 常量n:
    语句组n;break;
  default:
    语句组n+1;
}

 

例:

package basic;
public class SwitchStatement {
	public static void main(String args[]) {
		scoreToLevelTest();
	}

	public static char scoreToLevel(int paraScore) {
		char resultLevel = 'E';
		int tempDigitalLevel = paraScore / 10;
		switch (tempDigitalLevel) {
		case 10:
		case 9:
			resultLevel = 'A';
			break;
		case 8:
			resultLevel = 'B';
			break;
		case 7:
			resultLevel = 'C';
			break;
		case 6:
			resultLevel = 'D';
			break;
		case 5:
		case 4:
		case 3:
		case 2:
		case 1:
		case 0:
			resultLevel = 'F';
			break;
		default:
			resultLevel = 'E';
		}

		return resultLevel;
	}
	public static void scoreToLevelTest() {
		int tempScore = 100;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));

		tempScore = 91;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));

		tempScore = 82;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));

		tempScore = 75;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));

		tempScore = 66;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));

		tempScore = 52;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));

		tempScore = 8;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));

		tempScore = 120;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值