Using regex for switch-statement in Java

后端 未结 2 661
小蘑菇
小蘑菇 2020-12-16 11:38
void menu() {
    print();
    Scanner input = new Scanner( System.in );
    while(true) {
        String s = input.next();
        switch (s) {
        case \"m\":          


        
相关标签:
2条回答
  • 2020-12-16 12:02

    You can't use a regex as a switch case. (Think about it: how would Java know whether you wanted to match the string "[A-Z]{1}[a-z]{2}\\d{1,}" or the regex?)

    What you could do, in this case, is try to match the regex in your default case.

        switch (s) {
            case "m": print(); continue;
            case "s": stat(); break;
            case "q": return;
            default:
                if (s.matches("[A-Z]{1}[a-z]{2}\\d{1,}")) {
                    filminfo( s );
                }
                break;
        }
    

    (BTW, this will only work with Java 7 and later. There's no switching on strings prior to that.)

    0 讨论(0)
  • 2020-12-16 12:11

    I don't think you can use regex in switch cases.

    The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used.

    See http://download.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html for more info.

    0 讨论(0)
提交回复
热议问题