gpt4 book ai didi

java - java 将 if-else 转换为 switch 语句

转载 作者:行者123 更新时间:2023-11-30 01:53:27 26 4
gpt4 key购买 nike

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

我的挑战是这部分:

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 或字符串 vs int..

最佳答案

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
}

是一个选项。

关于java - java 将 if-else 转换为 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55276216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com