Search code examples
javaoopenumsswitch-statemententer

How do I make it so that the user can choose the gender of a person?


Please tell me, I put a variable in the enum constructor that shows the gender of a person male and female. I want the user to choose what gender They will be. For Example, 1-Husband, 2-Wife. How do I do this?

        
 
        Gender gen =  Gender.MAN;
 
        Person person1 = new Person(gen);
        
        
        ArrayList <Person> people = new ArrayList<>();
        
        people.add(person1);
 
        
    }
}```

```  public class Person {
    private  Gender gen;
    
  
    public Person ( Gender gen){
    
        this.gen = gen;
      
      
  }```


``` public enum Gender {
    MAN("Man"),
    WOMAN("Woman");
    private String translation;
    
    Gender(String translation){
        this.translation = translation;
        
    }
    
    public String getGender(){
        return translation;
        
    }
    
    
} ```

Solution

  • Artemy, Is this what you mean?

    public enum Gender {
        MAN("Man", "1", "M"),
        WOMAN("Woman", "2", "W");
    
        private List<String> translation;
    
        Gender(String... translation) {
            this.translation = Arrays.asList(translation);
        }
    
        public static Gender getGender(String value) {
            if (MAN.translation.contains(value)) {
                return MAN;
            } else if (WOMAN.translation.contains(value)) {
                return WOMAN;
            }
            throw new IllegalArgumentException(value);
        }
    }