开关案例语句中的使用方法 [英] using method in switch case statements

查看:257
本文介绍了开关案例语句中的使用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在切换情况下是否可以使用诸如'contains()'之类的方法.我正在尝试将以下if语句放入切换用例:

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
}

非常感谢您的帮助.

推荐答案

实际上,您可以将其更改为switch,但是有点难以理解:

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
    }
}

这篇关于开关案例语句中的使用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆