4

How to use the inputs of string array in 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;                  
}
Mandar Pandit
  • 2,171
  • 5
  • 36
  • 58
user3739889
  • 51
  • 1
  • 2
  • 1
    You can't use array in a switch statement. – rds Jun 14 '14 at 08:01
  • 2
    What you're talking about doesn't seem logical. You initialize an array with all these values and then "switch" them? *And* you have the same statements in both "January" *and* "February"?? Think about it...the array has all these values; so what is it switching??? – ChiefTwoPencils Jun 14 '14 at 08:01
  • How can you check array object in switch? – Kanagaraj M Jun 14 '14 at 08:03

3 Answers3

7

Java (before version 7) does not support String in switch case. But you can achieve the desired result by using an 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...
}

Please see here for more info

Community
  • 1
  • 1
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
2

Since JDK 7 you can have a String in a switch. but not a String array....

here's an example

in your code, you're trying to put the whole array into the switch. try this:

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;
    }
orenk86
  • 720
  • 9
  • 24
0

You cannot use an array in a switch statement (before Java 7). If you are using Java 6 for Android development, you cannot switch on Strings either. Its better you use an enumeration for the months, then switch on the enumeration.

ufuoma
  • 237
  • 1
  • 7
  • Strings in switches doesn't occur until 7, so yes *any* "Java" development cannot contain these prior to that. None of that was stated. – ChiefTwoPencils Jun 14 '14 at 08:09