简体   繁体   English

getGender()使用isMale返回null

[英]getGender() returning null with isMale

Whenever I run the getGender() it shows as null . 每当我运行getGender()它都显示为null It's the isMale that confuses me. isMale我困惑的isMale

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. 我已经使它能够返回一个值,但它将其返回为“true”或“false”,并且不将其作为“Male”或“Female”返回,但这是将其返回为null的代码。 I'm at a standstill. 我处于停滞状态。

Your constructor doesn't set your field String gender . 您的构造函数未设置字段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. 您的isMale变量指示该人是否为男性。

You should change the getGender method so that it will return "Male" when isMale == true and "Female" when isMale == false. 您应该更改getGender方法,以便在isMale == true时返回“Male”,在isMale == false时返回“Female”。

   /**
     * 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. 没有任何内容可以设置您班级中的gender字段。

In general, you shouldn't have both an isMale variable and a gender variable. 通常,您不应该同时拥有isMale变量和gender变量。 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). 你可以从另一个派生出一个,而isMale是一个更好的实现,因为你只有两个状态(这里不是试图反转,这只是大多数学生作业的基本假设)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM