Enhanced 'switch' blocks are not supported at language level 7 - Android Studio

Viewed 5153

I have used a switch statement that takes string values from a spinner. Now, there are a lot of such string values. It looks something like this:

switch (spin.getSelectedItem()) {
    case "first option", "second option", "third option":
         result = 1;
         break;
    case "fourth option", "fifth option", "sixth option":
         result = 2;
         break;
    case "seventh option", "eighth option", "ninth option";
         result = 3;
         break;
}

However, an error appears saying that enhanced switch blocks are not supported at language level 7. I have tried changing the source compatibility and target compatibility in the module settings, but it still doesn't work. Any advice and help is highly appreciated.

1 Answers

The part that isn't supported is this:

case "first option", "second option", "third option":

They are multivalue labels, and are indeed not supported prior to Java 14, where they became standard.

What you need instead is this:

switch (spin.getSelectedItem()) {
    case "first option":
    case "second option":
    case "third option":
        result = 1;
        break;
    /** rest of the code here
}

If you don't have a break keyword after label, the switch by default "falls through" to the next label below it.

Related