Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

How to set an attribute of an object to only accept a number of values

So in java the boolean primitive data type can only hold two values : true or false. So now I want to make a class that has an attribute such as gender, and it will only allow two values. Is that possible

1 Answer

Hi there,

Yes! Have a read around the enum, for example here.

Or just an if statement. Something like:

String gender; // could be passed into a method too
if (gender.equals("Male") || gender.equals("Female")){
  console.printf("gender set as %s", gender);
} else {
  console.printf("%s is an invalid value - try again", gender);
}

There are probably other ways too. The enum is the more elegant, in my view.

Hope that helps,

Steve.