每当我运行 getGender() 时,它​​都会显示为 null 。是 isMale 让我感到困惑。

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

我使它能够返回一个值,但它返回它为“真”或“假”,而不是将它返回为“男”或“女”,但这是将其返回为空的代码。我处于停滞状态。

最佳答案

您的构造函数没有设置您的字段 String gender 。你可以,

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
}

当然,那么你的输出可能是
Male: Female

所以,我想你真的想要
// System.out.println("Male: " + getGender());
System.out.println("Gender: " + getGender());

然后你会得到
Gender: Male

或者
Gender: Female

关于java - getGender() 用 isMale 返回 null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26618378/

10-13 09:16