Infinite_Loop
Infinite_Loop

Reputation: 380

Switch statement with enum in Java

I hope someone can direct me to the right direction.

I have the below code in enum with department names and their codes. I want to be able to print the departments' full names with their descriptions on the screen. I want to accomplish that by using a switch statement, but I am unsure where to place the switch statement.

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

Any help is appreciated.

Upvotes: 1

Views: 127

Answers (2)

Alex Kartishev
Alex Kartishev

Reputation: 1856

To String should be following:

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

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

I want to be able to print the departments' full names with their descriptions on the screen.

You need to associate the full name with each enum value. The simplest way of doing it is to add a description member to the 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();
    }
}

I want to accomplish that by using a switch statement

That would be a wrong way of doing that, because the association with the name would be external to the enum (i.e. no longer be encapsulated). The consequence of this is that each time you add a new enum member, all your switches that depend on that enum would need to change. Moreover, the compiler would not be able to help you catch places where you missed the new enum value.

Upvotes: 4

Related Questions