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;                  
}
3
  • 1
    You can't use array in a switch statement. Commented Jun 14, 2014 at 8: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??? Commented Jun 14, 2014 at 8:01
  • How can you check array object in switch? Commented Jun 14, 2014 at 8:03

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

4 Comments

What is fruit here - switch(fruit)?
You probably wrote a good answer, but where does the fruit variable come from?
Funny, I thought fruit was a purposeful distraction.
@11684 I had similar problem earlier,and fruit was in my code,just typo.
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;
    }

Comments

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.

1 Comment

Strings in switches doesn't occur until 7, so yes any "Java" development cannot contain these prior to that. None of that was stated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.