我的日食一直说“没有使用该领域的价值”

问题描述 投票:0回答:2

我的Person类中有一个(boolean)hasDriverLicence变量。我创建了getter和setter方法,并且在人员构造函数中使用了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);

这里是吸气剂和二传手:

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 "";
}
java class constructor boolean getter-setter
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在第二个因此,永远不会实现)。


-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.