Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using method in switch case statements

I was wondering if you could use methods such as 'contains()' in the case of a switch case. I am trying to make the following if statements into a switch case:

String sentence;
if(sentence.contains("abcd")){
// do command a
}
else if(sentence.contains("efgh")){
// do command b
}
else if(sentence.contains("ijkl")){
// do command c
}
else{
//do command d
}

Thank you very much for your help.

like image 467
Flissie Avatar asked Oct 31 '22 07:10

Flissie


2 Answers

actually you can change this if into switch, but its kinda unreadable:

    final String sentence;
    int mask = sentence.contains("abcd") ? 1 : 0;
    mask |= sentence.contains("efgh") ? 2 : 0;
    mask |= sentence.contains("ijkl") ? 4 : 0;
    switch (mask) {
    case 1:
    case 1 | 2:
    case 1 | 4:
    case 1 | 2 | 4:
        // do command a
        break;
    case 2:
    case 2 | 4:
        // do command b
        break;
    case 4:
        // do command c
        break;
    default:
        // do command d
    }
}
like image 67
Iłya Bursov Avatar answered Nov 10 '22 15:11

Iłya Bursov


No, because the case constant must be either:

  • A constant expression
  • Or the name of an enumerator of the same type as the switch expression.

A method call is neither of these.

From the Java Language Specification, section 14.11: The switch statement:

Every case label has a case constant, which is either a constant expression or the name of an enum constant.

like image 44
Andy Thomas Avatar answered Nov 10 '22 15:11

Andy Thomas