gpt4 book ai didi

java - 如何将充满 if 语句的 for 循环更改为更优雅/高效的代码?

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

这是我的字符串:

String field = "first=true, second=true"

我的方法对这个字符串进行操作并识别它是否包含 first=second= 子字符串,如果是 - 基于它调用其他方法之后的真/假。不过,第一个和第二个子串可能是可选的。这是我到目前为止:
void method(String field) {

String[] splittedField = field.split(", ");
for (String substring : splittedField) {
if (substring.contains("first") {
if (substring.contains("true") {
otherMethod("first", "true");
} else if (substring.contains("false") {
otherMethod("first", "false");
}
} else if (substring.contains("second") {
if (substring.contains("true") {
otherMethod("second", "true");
} else if (substring.contains("false") {
otherMethod("second", "false");
}
}
}

}

但也许有更好/更有效(和优雅?)的方法来解决这个案例?

最佳答案

考虑:

if (substring.contains("first") {
if (substring.contains("true") {
otherMethod("first", "true");
} else if (substring.contains("false") {
otherMethod("first", "false");
}
}

上面的 if 可以编码为:
if (substring.contains("first") {
String[] valueString = substring.split("=");
otherMethod("first", valueString[1]);
}

关于java - 如何将充满 if 语句的 for 循环更改为更优雅/高效的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60564862/

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