java - Java 替代看起来很糟糕的 if-else 或 switch 结构
问题描述
寻找实现字符串翻译的现代方法来替换难看的 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;
[...]
解决方案
你可能想要一个enum
.
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();
推荐阅读
- jmeter - JMeter 如果控制器不工作
- javascript - 与外部 react.js 捆绑不起作用 - 可能缺少一些全局变量?
- java - 无法从此列表中找到要调用的 maven() 方法:
- sql - 将数据加载到 PDW 上的临时表中
- python - 跟随抓取的链接
- r - 将 data.frames 列表中的列表取消列出到单个 data.frame
- android - 如何证明像诗一样的文字?
- java - Android Studio 3.1.2 - 无法运行 C++ 子例程“找不到 Java.lang.String 的实现...”
- python - python流控制功能奇怪
- delphi - Delphi Tokyo 将与 Advantage Database 11x 一起使用吗