day5:基本switch语句以及case、break、default的用法

相关要点:

switch语句的语法形式:

swtich(表达式){

          case 常量1:

                  语句组1;(break;)

             ......

          case 常量n:

                  语句组n;

          default:

                  语句组n+1;

}

注意:

①switch语句可以实现多重判断

②“表达式”的数据类型必须是byte、short、char、int、枚举或者String;

③“常量”的数据类型同上,注意不包括long型

break 语句可以提前结束switch的执行,否则会一直执行

⑤如果都不满足“常量”的条件,则执行default语句。default语句也可以不写。

根据学生的百分成绩给出成绩等级。

package test;

/**
 * The usage of the switch statement.
 * 
 * @author 前夜
 */
public class SwitchStatement {

	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args not used now.
	 *********************
	 */
	public static void main(String args[]) {
		scoreToLevelTest();
	}// Of main

	/**
	 *********************
	 * Score to level.
	 * 
	 * @param paraScore From 0 to 100.
	 * @return The level from A to F.
	 *********************
	 */
	public static char scoreToLevel(int paraScore) {
		// E stands for error, and F stands for fail.
		char resultLevel = 'E';

		// Divide by 10, the result ranges from 0 to 10
		int tempDigitalLevel = paraScore / 10;

		// The use of break is important.
		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';
		}// Of switch

		return resultLevel;
	}// of scoreToLevel

	/**
	 *********************
	 * Method unit test.
	 *********************
	 */
	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));

	}// Of scoreToLevelTest

}// Of class SwitchStatement

备注:在一开始我并不理解为什么要写成两个函数,现在我觉得如果只写成一个函数,不方便进行多个数据测试。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值