繁体   English   中英

我的日食一直说“不使用字段的值”

[英]My eclipse keep saying “The value of the field is not used”

我的Person类中有一个(boolean)hasDriverLicence变量。 我创建了getter和setter方法,并且在person构造函数中使用了hasDriverLicence,但是在日食中说“未使用字段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 "";
}

您在吸气剂中有错字。 您的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 { 

    // ...
}

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

single =编译,但IDE会警告您声明从未使用该变量,原因是赋值运算符返回赋值

例如,以下语句:

myVariable = 1  

...返回1

因此,当您错误地检查分配( = )而不是原始相等性( == )时,将始终检查分配的 (在您的情况下,在始终满足的第一个条件下为true ,在false条件下为false 。第二,因此将永远无法实现)。

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

暂无
暂无

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

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