首页 > 解决方案 > 如何在 Java 的 Switch 的 Case 值中添加字符串数组项?

问题描述

我们知道,从 Java 7 开始,Switch 的表达式可以是 String。所以我正在制作一个应用程序,当用户选择一个类别时,他/她将根据类别值被分配到相关部门。这是代码: -

    public class Selector {
    ///String array to save the departments
    private final static String[] DEPTS = {
            "A",
            "B",
            "C",
            "D"
    };

    //String array for the categories
    private final static String[] CATEGORY = {
            "Wind",
            "Air",
            "Fire",
            "Cloud",
            "River",
            "Tree",
            "Abc",
            "Def"
    };

    //return the department when user selects a particular category item from above
    public static String setDepartment(String category) {
        switch(category){
            case "Wind":
                return DEPTS[0];
            case "Air":
                return DEPTS[1];
            case "Fire": case "Cloud": case "River":
                return DEPTS[2];
            case "Tree": case "Abc": case "Def":
                return DEPTS[3];            
        }
        return null;
    }
}

所以我在想如何使用部门的数组索引返回部门项目,我可以在案例值中使用相同的东西,比如,

case CATEGORY[0]: case CATEGORY[1]: 
     return DEPTS[2];

因为如果类别项目包含一个大字符串,那么案例将变得太长而无法写入。如果java不允许这样做,你能建议一些其他的方法,这样我的代码就不会变得麻烦吗?谢谢。

标签: javaarraysstringswitch-statement

解决方案


你为什么不使用枚举来做到这一点。

public class Selector {

  private enum DepartmentCategory = {
    Wind("A"),
    Air("B"),
    Fire("C"),
    Cloud("C"),
    River("C"),
    Tree("D"),
    Abc("D"),
    Def("E");

    private String department;

    DepartmentCategory(String department) {
      this.department = department;
    }
    public String getDepartment() {
      return department;
    }
  };
}

现在如果给你一个部门,你可以通过以下代码轻松获取类别。

String category = "Wind";
DepartmentCategory dc = DepartmentCategory.valueOf(category);
dc.getDepartment(); // Returns the department

推荐阅读