Using regex for switch-statement in Java

后端 未结 2 669
小蘑菇
小蘑菇 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.)

提交回复
热议问题