我想知道在 switch 情况下是否可以使用“contains()”等方法。我正在尝试将以下 if 语句放入 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
}
非常感谢您的帮助。
最佳答案
实际上你可以把这个 if 改成 switch,但它有点不可读:
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
}
}
关于java - 在 switch case 语句中使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35949723/