我希望有人能指引我正确的方向。
我在枚举中有以下代码,其中包含部门名称及其代码。我希望能够在屏幕上打印部门的全名及其描述。我想通过使用 switch 语句来实现,但我不确定将 switch 语句放在哪里。
enum DepartmentName {
FINANCE ("FIN")
, SALES ("SAL")
, PAYROLL ("PYR")
, LOGISTIC ("LGT")
;
private final String department;
DepartmentName(String abbr) {
department = abbr;
}
public String getDepartmentCode() {return department;}
@Override
public String toString() {
return "The department name is " + getDepartmentCode();
}
}
感谢任何帮助。
最佳答案
I want to be able to print the departments' full names with their descriptions on the screen.
您需要将全名与每个 enum
值相关联。最简单的方法是向 enum
添加一个 description
成员:
enum DepartmentName {
FINANCE ("FIN", "Finance")
, SALES ("SAL", "Sales")
, PAYROLL ("PYR", "Payroll")
, LOGISTIC ("LGT", "Logistic")
;
private final String department;
private final String description;
DepartmentName(String abbr, String full) {
department = abbr;
description = full;
}
public String getDepartmentCode() {return department;}
public String getDescription() {return description;}
@Override
public String toString() {
return "The department name is " + getDepartmentCode();
}
}
I want to accomplish that by using a switch statement
那将是一种错误的做法,因为与名称的关联将在 enum
外部(即不再被封装)。这样做的结果是,每次添加新的 enum
成员时,所有依赖于该 enum
的 switches
都需要更改。此外,编译器无法帮助您捕捉到您错过了新的 enum
值的地方。
关于java - Java 中带枚举的 Switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647628/