1

我的 Person 类中有一个 (boolean)hasDriverLicence 变量。我创建了 getter 和 setter 方法,并在 person 构造函数中使用了 hasDriverLicence,但我的 Eclipse 说“未使用字段 Person.hasDriverLicence 的值”。这是代码:

public Person(int id, String firstName, String lastName, String gender, Calendar birthDate, String maritalStatus,
        String hasDriverLicence) throws Exception {

    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDate = birthDate;

    setGender(gender);
    setMaritalStatus(maritalStatus);
    setHasDriverLicence(hasDriverLicence);

这是getter和setter:

public void setHasDriverLicence(String hasDriverLicence) throws Exception {

    if (!(hasDriverLicence.equalsIgnoreCase("Yes")) && !(hasDriverLicence.equalsIgnoreCase("No")))

        throw new Exception("Wrong input, please type Yes or No");

    if (hasDriverLicence.equalsIgnoreCase("Yes")) {

        this.hasDriverLicence = true;

    }

    else if (hasDriverLicence.equalsIgnoreCase("No")) {

        this.hasDriverLicence = false;

    }
}

public String getHasDriverLicence() {

    if (this.hasDriverLicence = true)

        return "Yes";

    if (this.hasDriverLicence = false)

        return "No";

    else

        return "";
}
4

2 回答 2

2

您在吸气剂中有错字。您的if条件实际上设置了实例字段的值,而不是检查它:

if (this.hasDriverLicence = true)

这应该是:

if (this.hasDriverLicence == true)

或者更好的是:

if (this.hasDriverLicence) {
    // ...
// no need for a separate if statement for the opposite condition,
// and you can only have two states here
else { 

    // ...
}

因此,该变量已分配但从未在您的代码中使用。

细化

单次=编译但 IDE 向您发出警告称该变量从未使用过的原因是赋值运算符返回分配的值

例如,声明:

myVariable = 1  

...返回1

因此,当您错误地检查赋值 ( =) 而不是原始相等 ( ==) 时,您将始终检查赋值的(在您的情况下,true第一个条件将始终满足,false在第二个条件中,因此将永远不满足)。

于 2019-03-11T14:16:50.683 回答
-1

也许你可以尝试重建你的工作区。我看不到上述代码的问题。

于 2019-03-11T14:19:27.420 回答