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.
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
}
}
No, because the case
constant must be either:
switch
expression.A method call is neither of these.
From the Java Language Specification, section 14.11: The switch statement:
Every
case
label has acase
constant, which is either a constant expression or the name of an enum constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With