GetGender () returns null with isMale

Whenever I run getGender(), it displays as null. It isMalebothers me.

public Student(String sid, String name,  boolean isMale)
{       
    this.sid = sid;
    this.name = name;
    this.isMale = isMale;
    courses = "30202";  // default is empty
}

I made it so that it can return a value, but it returns it as "true" or "false" and does not return it as "Male" or "Female", but this is a code in which it returns it as null, I'm at a dead end.

+4
source share
3 answers

Your constructor does not set your field String gender. Could you,

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 conclusion may be

Male: Female

So, I think you really wanted to

// System.out.println("Male: " + getGender());
System.out.println("Gender: " + getGender());

Then you get

Gender: Male

or

Gender: Female
+4
source

Your isMale variable indicates whether the person is isMale or not.

getGender, "", isMale == true "Female", 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;
    }
+1

, gender .

In general, you should not have a variable isMaleand a variable gender. It's too much. You can get one from the other, and the isMalebest implementation is because you have only two conditions (do not try to be anti-trance here, this is just the main assumption in most student assignments).

0
source

All Articles