0.主题
今天用一个将百分制成绩转为等级制的程序来熟悉基本switch语句的使用,java中switch语句的使用和C/C++中是一样的。首先附上代码。
package basic;
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
程序的执行结果如下
该程序中分数与等级的对应情况如下表
分数区间 | 等级 |
---|---|
90~100 | A |
80~89 | B |
70~79 | C |
60~69 | D |
0~59 | F |
非法输入 | E |
这样的形式很容易想到使用if/else结构来处理,但当分支过多时,这种结构多少显得有些笨拙,switch无疑更适合应用在此处场景。
1.switch语句
switch 语句将从第一个与选项值相匹配的 case 标签处开始执行,直到执行完剩下的所有语句,或遇到break为止。以上文程序为例
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
如果将case9之后的break语句取消,那么当匹配到9时,程序会先执行case 9后的resultLevel = 'A'; 紧接着继续执行case 8后的resultLevel = 'B'; 然后遇到break而退出,最后给出的即是错误的答案。因此,合理正确的使用break才能得到正确的程序。
第二个需要注意的是default的使用,仍以上文程序为例,成绩范围是[ 0, 100 ],当输入的成绩不在此范围内时,不能与任何case相匹配,此时执行default之后的语句,通过等级' E '给出反馈。
在实际生活中,程序或多或少会收到一些非法输入,面对这样的输入,算法应该要能够做出适当的反映或进行相应的处理,这称之为算法的健壮性,此处default的使用正是提供了这一保障。
2.其他
单元测试应当单独使用一个方法,而不是将它放入main方法中。