r/javahelp • • Sep 30 '19

Quick beginner question: let’s say I scan the users answer to “what is your gender?” A) Male B) Female How do I store A as “male”?

I want to follow up with a question: Gender: Male Is this correct?

23 Upvotes

17 comments sorted by

View all comments

Show parent comments

1

u/mk321 Sep 30 '19

You can create enum with values (Strings):

enum Gender {
    MALE("male"),
    FEMALE("female");
    
    private final String value;
 
    private Gender(String value) {
        this.value = value;
    }
}

And check it in this way:

if (input.equals(Gender.MALE.value()) {
    gender = Gender.MALE;
} else if (input.equals.FEMALE.value()) {
    gender = Gender.FEMALE;
}

Or you can write your own method valueOfString in your enum (because valueOf in Java based on enum name: Gender.valueOf("MALE") so you lose the advantage of values in enums and have to uppercase input):

public Gender valueOfString(String gender) {
    for (Gender g : values()) {
        if (g.value.equals(label)) {
            return g;
        }
    }
    return null;
}

And you can use it simply:

gender = Gender.valueOfString(input);