简体   繁体   中英

How to compare the value of enumeration in JAVA

I wanted to create something when the user login, if the login as User then it go into the first module else if the user login as admin it goes into the second module. The question is I have no idea on how to compare the user role by using enum.

for(int i = 0; i < staffCount; i++) {
    if(username.equals(staff[i].GetStaffID()) && pass.equals(staff[i].GetPassword()) && staff[i].GetUserRole().equals("User")){
        System.out.println("hello user");
    }
}

Here is my enum declaration in Staff class

enum userRole{
    Admin,
    User
}

Here is the setter and getter

public void SetUserRole(userRole userRole){
    this.userRole = userRole;
}

public userRole GetUserRole(){
    return userRole;
}

Instead of

staff[i].GetUserRole().equals("User")

You probably mean

staff[i].GetUserRole().equals(userRole.User)

or

staff[i].GetUserRole() == userRole.User

As a side note, according to Java's naming conventions, the enum should really be named UserRole , and its values ADMIN and USER . Like this:

enum UserRole {
    ADMIN,
    USER
};

replace staff[i].GetUserRole().equals("User")

with staff[i].GetUserRole() == userRole.User

because they refer to the same instance you can use == instead of .equals

also like Feredrico klez Culloca said, you should look into naming convention, constants like enum names tend to be in all caps, enums and classes and interfaces tend to be capitalized, and variable names and methods tend to be camelcase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM