使用字符串进行切换时出错

时间:2014-10-22 17:03:05

标签: java string switch-statement

当我尝试使用String进行切换时,收到错误消息。这是错误:

incompatible types found: 
java.lang.String 
required: int 
switch(monthName){

这使得我似乎只能使用int进行切换,但我很确定在最近的Java版本中,您可以使用String进行切换。这是给我错误的代码:

switch(monthName){
        case "December"://Always has 31 days
            daysLeft = 31;
            daysLeft -= dayOfMonth;
            break;
        case "November"://Always has 30 days
            daysLeft = 61;
            daysLeft -= dayOfMonth;
            break;
        case "October"://Always has 31 days
            daysLeft = 92;
            daysLeft -= dayOfMonth;
            break;
        case "September"://Always has 30 days
            daysLeft = 122;
            daysLeft -= dayOfMonth;
            break;

2 个答案:

答案 0 :(得分:2)

如果源级别低于1.7,则无法为String类型的值打开。只允许使用可转换的int值或枚举常量

答案 1 :(得分:0)

在班级中定义枚举:

public enum MonthName {
    December, November, October, September
}

使用val变量根据字符串输入提供开关功能 -

String val = "December";//can be taken from user through Scanner class
MonthName monthName = MonthName.valueOf(val);//Enum class object

switch (monthName) {
    case December://Always has 31 days
        daysLeft = 31;
        daysLeft -= dayOfMonth;
        break;
    case November://Always has 30 days
        daysLeft = 61;
        daysLeft -= dayOfMonth;
        break;
    case October://Always has 31 days
        daysLeft = 92;
        daysLeft -= dayOfMonth;
        break;
    case September://Always has 30 days
        daysLeft = 122;
        daysLeft -= dayOfMonth;
        break;
    }
    System.out.println(dayOfMonth + "---" + daysLeft);//Test of output
}