StringBuilder循环:可能尚未初始化局部变量

Ale*_*erc 0 java stringbuilder compiler-errors initialization

我有以下方法规范化给定的XML标记名称:

public static String normaliseTagName(String tagName) {
    // Return a given empty tag name.
    if (tagName.length() == 0) {
        return tagName;
    }

    // Replace invalid start.
    if (isInvalidXMLStart(tagName.charAt(0))) {
        tagName = XML_REPLACEMENT + tagName;
    }

    // Replace invalid characters.
    StringBuilder normalised;
    boolean invalidFound = false;
    for (int i = 0; i < tagName.length(); i++) {
        if (isInvalidXMLChar(tagName.charAt(i))) {
            if (!invalidFound) {
                normalised = new StringBuilder(tagName.substring(0, i));
                invalidFound = true;
            }
            normalised.append(XML_REPLACEMENT); // COMPILER ERROR
        } else if (invalidFound) {
            normalised.append(tagName.charAt(i)); // COMPILER ERROR
        }
    }

    return invalidFound ? normalised.toString() : tagName; // COMPILER ERROR
}
Run Code Online (Sandbox Code Playgroud)

StringBuilder normalised在我确定使用它之前,我不想初始化它.换句话说,我只想在找到无效的XML字符时初始化它.

The local variable normalised may not have been initialized指出错误,我很困惑为什么编译器告诉我什么时候normalised显然从未使用过未初始化.

  1. 我错过了什么或编译器无法确定StringBuilder normalised这种情况下的初始化路径?
  2. 如果无法避免此编译错误,我该如何修改此代码以便StringBuilder在需要时才初始化?

谢谢!

Men*_*ena 5

您需要显式初始化本地变量:

StringBuilder normalised = null;
Run Code Online (Sandbox Code Playgroud)

... 要么 ...

StringBuilder normalised = new StringBuilder();
Run Code Online (Sandbox Code Playgroud)

......在引用它之前.

normalised初始化之前,代码引用中的一些路径:

normalised.append(...
Run Code Online (Sandbox Code Playgroud)

局部变量不会像实例字段那样自动初始化.