1.switch语句
选择语句包括if和switch,当多次使用if-else时,会使得代码的可读性降低,这时候用switch就可以简化代码增加可读性
switch (expression) {
case expression constants 1:
statement 1;
case expression constants 2:
statement 2;
break; // Optional
......
case expression constants n:
statement n;
break;
default: // Optional
statement n+1;
}// Of switch
其中expression必须计算出一个数据,然后执行与之对应case中的语句,如语句最后有break,则直接跳出switch,否则继续执行下一个case,在遇到break或者switch执行完成时结束
default也是可选择的,当出现除前面case之外的情况时,执行default后面的语句
2.switch的简单测试
这里是对一些成绩进行分级,0-59为'F',60-69为'D',70-79为'C',80-89为'B',90-100为'A',其余错误输入则输出'E'.
package basic;
/**
* This is the fifth code.
*
* @author Yunhua Hu yunhuahu0528@163.com.
*/
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
输出: