jeudi 21 mars 2019

convert if-else to switch statements java

i am trying to create switch statements for an address parser, that parses a String through a regex, but i am having difficulties with it.

here's the regex and the patternList, which is an Arraylist (or Linkedlist, i haven't decided:

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

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

how do i convert the following into switch statements?

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;

i've tried to do this:

        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();
}

but i get an error that the type chosen for the switch and the case don't match. e.g. boolean vs int or string vs int..

Aucun commentaire:

Enregistrer un commentaire