【发布时间】:2015-05-18 22:27:48
【问题描述】:
为什么编译失败,出现“case 表达式必须是常量表达式”的错误? null 不是常量(在编译时已知)吗?
像case ((String)null) 一样将null 值显式转换为String 也无济于事(我得到了同样的错误)。
public static String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case null:
typeOfDay = "NULL";
break;
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
【问题讨论】:
-
@BrunoParmentier 也是有用的链接。谢谢。
标签: java