java - 如何在 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不允许这样做,你能建议一些其他的方法,这样我的代码就不会变得麻烦吗?谢谢。
解决方案
你为什么不使用枚举来做到这一点。
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
推荐阅读
- python - 更新标记器后,LineByLineTextDataset 会一直加载
- python - 在 catplot 的条形图中显示数据标签的问题
- vaadin-flow - CSS 中的 URL 在 Vaadin 14.6 中不再有效
- azure - 使用 Filebeat 连接到 Microsoft Defender API 时出现错误 403 Forbidden
- python - numpy 的位运算函数的运行时复杂度是多少?
- swift - Swiftui - 在特定帧开始和停止场景视图动画
- kubernetes - 修复 Argo CD 中的不同步警告 - 无法忽略可选的“preserveUnknownFields”字段
- jupyter - 如何只有登录到我们网站的人才能访问 jupyterhub?
- android - Flutter Text Field:按住删除仅删除字符
- php - 如何从 laravel 传递 vue 中的道具?