Whenever I run the getGender()
it shows as null
. It's the isMale
that confuses me.
public Student(String sid, String name, boolean isMale)
{
this.sid = sid;
this.name = name;
this.isMale = isMale;
courses = "30202"; // default is empty
}
I have made it be able to return a value but it returns it as "true" or "false" and doesn't return it as "Male" or "Female" but this is the code in which returns it as null. I'm at a standstill.
Your constructor doesn't set your field String gender
. You could,
public Student(String sid, String name, boolean isMale){
this.sid = sid;
this.name = name;
this.isMale = isMale;
this.gender = (isMale) ? "Male" : "Female";
courses = "30202"; // default is empty
}
Of course, then your output might be
Male: Female
So, I think you really wanted
// System.out.println("Male: " + getGender());
System.out.println("Gender: " + getGender());
Then you would get
Gender: Male
or
Gender: Female
Your isMale variable indicates whether the person isMale or not.
You should change the getGender method so that it will return "Male" when isMale == true and "Female" when isMale == false.
/**
* Get the gender of the student, i.e. "Male" or "Female"
*
* @return The String "Male" if the student is male,
* otherwise "Female".
*/
public String getGender()
{
if(isMale) {
gender = "Male";
}
else{
gender = "Female";
}
return gender;
}
There is nothing that sets the gender
field in your class.
In general, you shouldn't have both an isMale
variable and a gender
variable. That's redundant. You can derive one from the other, and isMale
is a better implementation because you have only two states (not trying to be anti-trans here, that's simply the basic assumption in most student assignment).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.