转换if-else来切换语句java

问题描述 投票:1回答:1

我正在尝试为地址解析器创建switch语句,通过正则表达式解析String,但我遇到了困难。

我的挑战是这部分:

if(m.matches() && i==0){
            b.street(m.group(1));
            break;

如何使这成为

switch(SOMETHINGHERE) {
case SOMETHINGHERE: SOMECODE HERE
}

这里是正则表达式和patternList,它是一个Arraylist(或Linkedlist,我还没有决定:

static String streetReg = "([a-zæøåäöëüéèA-ZÆØAÄÖËÜÉÈ -./]*)";
static String symbolsReg = "[ ,.-]*";

public static void addPatterns() {
        patternList.add(Pattern.compile(streetReg + "" + symbolsReg));
    }

如何将以下内容转换为switch语句?

public static Address parse(String s) {
    addPatterns();
    Builder b = new Builder();
    boolean noMatch = false;
    for(int i = 0; i<patternList.size(); i++){
        Matcher m = patternList.get(i).matcher(s);

        if(m.matches() && i==0){
            b.street(m.group(1));
            break;
        }
        else if(m.matches() && i==1){
            b.street(m.group(1));
            b.city(m.group(2));
            break;
        }else if(m.matches() && i==2) {
            b.postcode(m.group(1));
            b.city(m.group(2));
            break;
        }else if(m.matches() && i== 3){
            b.street(m.group(1));
            b.house(m.group(2));
            b.city(m.group(3));
            break;

我试过这样做:

        switch (s){
            case "st":
                b.street(m.group(1));
                break;
            case "street and house":
                b.street(m.group(1));
                b.street(m.group(2));
                break;
            case "noMatch":
                noMatch =true;
                break;
        }
    }
if(noMatch)return null;
else return b.build();
}

但我得到的错误是为开关和外壳选择的类型不匹配。例如boolean vs int或string vs int ..

java parsing if-statement design-patterns switch-statement
1个回答
2
投票
if ( m.matches()) {
 switch(i) {
    case 0: b.street(m.group(1));
            checkNewVariable = true;
            break; // WARNING!! this break is a break for the switch, not for the FOR loop
    // you'll need to add a variable (checkNewVariable) so you can break after the switch if needed
   case 1: b.street(m.group(1));
           b.city(m.group(2));
           checkNewVariable = true;
           break;
// ... rest of your cases

  }

  if ( checkNewVariable ) { break; } // to break out of the for loop
}

是一种选择。

© www.soinside.com 2019 - 2024. All rights reserved.