将if-else转换为switch语句java

时间:2019-03-21 08:19:14

标签: java parsing if-statement design-patterns switch-statement

我正在尝试为地址解析器创建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();
}

但是我得到一个错误,该错误是为开关选择的类型和大小写不匹配。例如布尔值vs整数或字符串vs整数。

1 个答案:

答案 0 :(得分: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
}

是一个选择。