12

So what I am trying to do is this:

Write a User class

A User:

  • has a username e.g 'fj3'
  • has a userType which can be: 'user', 'editor' or 'admin'
  • has a name e.g 'Francis'
  • has a constructor which takes the username, userType and name as parameters
  • has a getUsername() method
  • has a getUserType() method
  • has a getName() method
  • has a setUserType() method which takes one of the user types as a parameter

My code so far:

public class User{

     public String id;
     public String userPermissions;
     public String actualName;

     public User(String username, String userType, String name){
         id = username;
         userPermissions = userType;
         actualName= name;
     }

    public String getUsername(){
        return id;
    }

    public String getUserType(){
        return userPermissions;
    }       

    public String getName(){
        return actualName;
    }

    public enum UserType{
       admin, editor, user;
    }

    public void setUserType(String input){
        userPermissions = input;
    }
}

What do I need to do to get this to work? I do not know how to make it so the only usertypes that can be chosen are admin, editor or user.

4

2 回答 2

11

You have to change your types to this enum:

public class User {
     public enum UserType {
        ADMIN, EDITOR, USER;
     }

     public String id;
     public UserType userPermissions;
     public String actualName;

     public User(String username, UserType userType, String name) {
         id = username;
         userPermissions = userType;
         actualName= name;
     }

    public String getUsername() {
        return id;
    }

    public UserType getUserType() {
        return userPermissions;
    }       

    public String getName() {
        return actualName;
    }

    public void setUserType(UserType input) {
        userPermissions = input;
    }
}
于 2013-11-09T17:45:05.577 回答
1

Because you have already declared an enum type to represent the possible values for userType, you've already gone a long way to solving this problem.

If you declare a variable of type UserType, then the only possible values must be one of the defined enum constants.

To restrict the input to your setPermissions method, all you have to do is change to the following:

public class User{

    public String id;
    public String userPermissions;
    public String actualName;

    public User(String username, String userType, String name){
        id = username;
        userPermissions = userType;
        actualName = name;
    }

    public enum UserType{
        ADMIN, EDITOR, USER;
    }

    public void setUserType(UserType type){
        userPermissions = type.toString();
    }
}
于 2013-11-09T18:08:28.853 回答