簡體   English   中英

用Java中的enum切換語句

[英]Switch statement with enum in Java

我希望有人可以指引我正確的方向。

我在帶有部門名稱及其代碼的枚舉中包含以下代碼。 我希望能夠在屏幕上打印部門的全名及其描述。 我想通過使用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();
    }
}

任何幫助表示贊賞。

我希望能夠在屏幕上打印部門的全名及其描述。

您需要將全名與每個enum值相關聯。 最簡單的方法是將description成員添加到enum

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();
    }
}

我想通過使用switch語句來實現

這將是錯誤的方法,因為與名稱的關聯將在enum外部(即不再被封裝)。 這樣的結果是,每次添加新的enum成員時,所有依賴於該enum switches都需要更改。 此外,編譯器將無法幫助您找到錯過新enum值的地方。

To String應該如下:

public String toString() {
    switch (this) {
        case FINANCE:
            return "finance";
        case SALES:
            return "sales";
        case PAYROLL:
            return "payroll";
        ... // and so on
    }
    return this.name();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM