如何在Android中的switch case中使用String []输入?

时间:2014-06-14 07:59:18

标签: java switch-statement arrays

如何在switch case中使用字符串数组的输入?

String[] mon=new String[]{"January","February","March","April","May","June","July","August","September","October","November","December"};

switch (mon)
{
    case "January":
        m=1;
        break;
    case "February":
        m=1;
        break;                  
}

3 个答案:

答案 0 :(得分:7)

Java(版本7之前)不支持switch案例中的String。但是,您可以使用enum来获得所需的结果。

private enum Mon {
   January,February,March,April,May,June,July,August,September,October,November,December
};

String value; // assume input
Mon mon = Mon.valueOf(value); // surround with try/catch

switch(mon) {
    case January:
        m=1;
        break;
    case February:
        m2;
        break;
    // etc...
}

有关详细信息,请参阅here

答案 1 :(得分:2)

自JDK 7起,您可以在String中拥有switch。但是不是一个String数组......

here's an example

在您的代码中,您尝试将整个阵列放入交换机。 试试这个:

String[] mon=new String[]{"January","February","March","April","May","June","July","August","September","October","November","December"};
String thisMonth = mon[5];
    switch (thisMonth)
    {
        case "January":
            m=1;
            break;
        case "February":
            m=2;
            break;
...
        case "June":
            m=6;
            break;
    }

答案 2 :(得分:0)

您不能在switch语句中使用数组(在Java 7之前)。如果您使用Java 6进行Android开发,则无法打开字符串。最好在几个月内使用枚举,然后打开枚举。