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

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

你可能感兴趣的:(java笔记,java)