switch语句是一种高效的多路语句,可以省掉很多繁杂的嵌套if判断;
在Java 6及之前,case语句中的常量只能是byte、char、short和int(也可以是对应的封装类)或枚举常量,在Java 7规范中增加了String,毕竟它也是常量类型;
Demo:
public class CoinSwitchString { public static void main(String[] args) {
printDay("Sunday");
printDay("Tuesday");
printDay("Ten");
} public static void printDay(String dayOfWeek) {
switch(dayOfWeek) {
case "Sunday": System.out.println("星期日"); break;
case "Monday": System.out.println("星期一"); break;
case "Tuesday": System.out.println("星期二"); break;
case "Wednesday": System.out.println("星期三"); break;
case "Thursday": System.out.println("星期四"); break;
case "Friday": System.out.println("星期五"); break;
case "Saturday": System.out.println("星期六"); break;
default: System.out.println("Error: '" + dayOfWeek + "' is not a day of the week!");
}
} }
Ran As Java Application:
星期日
星期二
Error: 'Ten' is not a day of the week!