空白的最终字段INITIAL可能尚未初始化

Koe*_*oen 10 java eclipse final

我用Java编程.我已经为每个方法添加了注释来解释他们应该做什么(根据作业).我已将我所知道的内容添加到Password.java(我在研究学校提供的javadoc后创建的存根)中.我的问题不是关于几个函数,我知道testWord和setWord中有错误,但我会自己处理.我的问题是关于这一行:

public static final java.lang.String INITIAL;
Run Code Online (Sandbox Code Playgroud)

这条线是由学校提供的,所以我必须假设它是正确的,我无法找到关于常数字段值INITIAL的任何文档,所以如果有人能够提供关于那将是惊人的信息(例如,如何是处理?它存储什么?如果有的话?键入?).我在Eclipse中的这一行上得到了一个错误:

空白的最终字段INITIAL可能尚未初始化

为什么这个错误在这里?提前感谢您的评论.

仅供参考Password.java的代码:

package ss.week1;

public class Password extends java.lang.Object {

// ------------------ Instance variables ----------------

/**
 * The standard initial password.
 */

public static final java.lang.String INITIAL;

// ------------------ Constructor ------------------------

/**
 * Constructs a Password with the initial word provided in INITIAL.
 */

public Password() {

}

/**
 * Tests if a given string is an acceptable password. Not acceptable: A word
 * with less than 6 characters or a word that contains a space.
 * 
 * @param suggestion
 * @return true If suggestion is acceptable
 */

// ------------------ Queries --------------------------

public boolean acceptable(java.lang.String suggestion) {
    if (suggestion.length() >= 6 && !suggestion.contains(" ")) {
        return true;
    } else {
        return false;
    }
}

/**
 * Tests if a given word is equal to the current password.
 * 
 * @param test Word that should be tested
 * @return true If test is equal to the current password
 */

public boolean testWord(java.lang.String test) {
    if (test == INITIAL) {
        return true;
    } else {
        return false;
    }
}

/**
 * Changes this password.
 * 
 * @param oldpass The current password
 * @param newpass The new password
 * @return true if oldpass is equal to the current password and that newpass is an acceptable password
 */

public boolean setWord(java.lang.String oldpass, java.lang.String newpass) {
    if (testWord(oldpass) && acceptable(newpass)) {
        return true;
    } else {
        return false;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 23

错误正是编译器所说的 - 你有一个最终字段,但没有设置它.

最后的字段需要被分配给恰好一次.你根本就没有分配它.我们不知道该字段在文档之外的含义是什么("标准初始密码") - 可能有一些默认密码,您应该知道.您应该将该值分配给该字段,例如

public static final String INITIAL = "defaultpassword";
Run Code Online (Sandbox Code Playgroud)

另外:你不需要写java.lang.String; 只需使用短名称(String).在代码中使用完全限定名称是非常好的主意; 只需导入您正在使用的类型,并注意所有内容java.lang都是自动导入的.

另外:不要使用比较字符串==; 使用.equals代替.

另外:任何时候你都有这样的代码:

if (condition) {
    return true;
} else {
    return false;
}
Run Code Online (Sandbox Code Playgroud)

你可以写:

return condition;
Run Code Online (Sandbox Code Playgroud)

例如,您的acceptable方法可以写成:

public boolean acceptable(String suggestion) {
    return suggestion.length() >= 6 && !suggestion.contains(" ");
}
Run Code Online (Sandbox Code Playgroud)