【问题标题】:My eclipse keep saying "The value of the field is not used"我的日食一直说“未使用该字段的值”
【发布时间】:2025-11-29 09:25:01
【问题描述】:

我的 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 "";
}

【问题讨论】:

  • 不确定我是否应该以拼写错误的形式关闭,但我的回答比评论长一点。如果有人费心找到一个,可能也会有一个 gazillon 欺骗。
  • 仅作记录:“有驾驶执照”应该是布尔值,而不是字符串。当该字段为真时,您想要打印“是”的事实与格式有关。您的代码将其混合在一起。格式应该存在于不同的位置,并且如前所述:该字段应该具有布尔类型!
  • FWIW,只需从getHasDriverLicence() 制作一个单行线 --> return this.hasDriverLicense ? "Yes" : "No";
  • 请勿使用Exception,除非您有需要它的现有 API 合约。 IllegalArgumentException 是这里的正确选择。

标签: java class constructor boolean getter-setter


【解决方案1】:

您在 getter 中有错字。 您的 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 在第二个条件中,因此永远不会满足)。

【讨论】:

  • 最好不要手动映射字符串。 “有驾驶执照”已经在命名级别上说信息应该是布尔值,而不是字符串。
  • @GhostCat 完全同意,但我只能解决这么多问题:D
  • @GhostCat 呵呵谢谢。正如 cmets 中提到的,我怀疑那里有很多骗子,至少按照宽松的标准。无论如何,预计这将很快关闭。
  • 开什么玩笑……一个“=”字符会改变一切,谢谢您的帮助。
  • 我也不能使用 boolean 类型的 hasDriverLicence 它必须是字符串。
【解决方案2】:

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

【讨论】:

    最近更新 更多