java - Java 中带枚举的 Switch 语句

标签 java enums

我希望有人能指引我正确的方向。

我在枚举中有以下代码,其中包含部门名称及其代码。我希望能够在屏幕上打印部门的全名及其描述。我想通过使用 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 成员时,所有依赖于该 enumswitches 都需要更改。此外,编译器无法帮助您捕捉到您错过了新的 enum 值的地方。

关于java - Java 中带枚举的 Switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647628/

相关文章:

Java .charAt(i) 比较问题

java - 在 Java 中读取 CSV 文件时跳过第一行

java - SpringBoot应用程序启动后启动@RabbitListener

c# - 从枚举值列表创建可检查上下文菜单的通用方法

ios - 使用枚举检查字符串

c# - 如何为枚举提供用户友好的名称?

java - 在哪里可以找到有关 Jetty API 的优质文档?

java - 如何找出 spring 托管 bean 的范围

java - EMF eclipse : enumeration with custom fields (properties)

c# - 如何查询在 NHibernate 中存储为枚举的标志