gpt4 book ai didi

糟糕的 if-else 或 switch 结构的 Java 替代方案

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:37 25 4
gpt4 key购买 nike

寻找现代方式来实现字符串转换以替换难看的 if-else 或 switch 结构:

if ("UK".equals(country)) 
name = "United Kingdom";
if ("GE".equals(country))
name = "Germany";
if ("FR".equals(country))
name = "France";
if ("IT".equals(country))
name = "Italy";
[...]

switch (country) {
case "UK": name = "United Kingdom"; break;
case "GE": name = "Germany" break;
case "FR": name = "France"; break;
case "IT": name = "Italy" break;
[...]

最佳答案

您可能需要一个枚举

public enum Country {
UK("United Kingdom"),
GE("Germany"), // sure this isn't DE?
FR("France");
// and so on
private String countryName;
private Country(String n) { countryName = n; }

public String getCountryName() { return countryName; }
}

现在你可以

Country c = Country.valueOf(countryString); // throws exception when unknown
name = c.getCountryName();

关于糟糕的 if-else 或 switch 结构的 Java 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53882290/

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