Day05
1. Background
今天是学习java的第五天了,今天需要学习的是Switch, case, break, default 的用法。
同时,老师对我们的代码提出了一个要求测试单独使用一个方法, main 方法里面的代码越少越好。
2. Description
总的来说,switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。
switch case 语句有如下规则:
- switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。
- switch 语句可以拥有多个 case 语句。每个 case 后面跟一个要比较的值和冒号。
- case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。
- 当变量的值与 case 语句的值相等时,那么 case 语句之后的语句开始执行,直到 break 语句出现才会跳出 switch 语句。
- 当遇到 break 语句时,switch 语句终止。程序跳转到 switch 语句后面的语句执行。case 语句不必须要包含 break 语句。如果没有 break 语句出现,程序会继续执行下一条 case 语句,直到出现 break 语句。
- switch 语句可以包含一个 default 分支,该分支一般是 switch 语句的最后一个分支(可以在任何位置,但建议在最后一个)。default 在没有 case 语句的值和变量值相等的时候执行。default 分支不需要 break 语句。
switch case 执行时,一定会先进行匹配,匹配成功返回当前 case 的值,再根据是否有 break,判断是否继续输出,或是跳出判断。
综上所述,java中switch的用法和C语言中差不多
3. Code
package basic;
/**
* This is the fifth code. Names and comments should follow my style strictly.
*
* @author Fan Min minfanphd@163.com
*/
public class Day05 {
/**
*******************
* 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 Day05
运行结果: