[英]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.我想在用户登录时创建一些东西,如果以用户身份登录,那么它将 go 进入第一个模块,否则如果用户以管理员身份登录,它将进入第二个模块。 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这是我在 Staff class 中的枚举声明
enum userRole{
Admin,
User
}
Here is the setter and getter这是 setter 和 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
.作为旁注,根据 Java 的命名约定,枚举实际上应该命名为UserRole
,它的值是ADMIN
和USER
。 Like this:像这样:
enum UserRole {
ADMIN,
USER
};
replace staff[i].GetUserRole().equals("User")
替换staff[i].GetUserRole().equals("User")
with staff[i].GetUserRole() == userRole.User
与staff[i].GetUserRole() == userRole.User
because they refer to the same instance you can use == instead of .equals
因为它们指的是同一个实例,所以您可以使用 == 而不是.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.也像 Feredrico klez Culloca 所说,你应该研究命名约定,像枚举名称这样的常量往往全部大写,枚举和类和接口倾向于大写,变量名称和方法往往是驼峰式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.