【问题标题】:'Cannot resolve symbol' when using an if/else statement使用 if/else 语句时“无法解析符号”
【发布时间】:2012-02-06 04:35:38
【问题描述】:

我只是想知道为什么我使用以下代码得到“无法解析符号初始文本”。 isItA 是一个布尔值,用户根据他们将要粘贴到文本区域的文本类型(A 或 B)提前选择它。 initialText 有 2 个可能的字符串,输出的一个取决于布尔值 isItA。当我在 if/else 语句之外使用 initialText 时,我不明白为什么会弹出此错误;如果在“if/else”语句内,编译器应该能够解析外面的字符串吗?我目前在 IntelliJ 中使用 GWT。在这一点上,我仍然是java的菜鸟,因此非常感谢您对为什么会发生这种情况的基本解释:)提前致谢。代码的 sn-p 如下。

protected TextArea getNewTextArea() {
    if ( newTextArea == null ) {

        if (isItA){
            final String initialText = "Please paste valid text A here, and then
            press" + "the \"" + Labels.ADD_A_BUTTON_TEXT + "\" button.";

        }else{
            final String initialText = "Please paste valid text B here, and then press " + "the \"" + Labels.ADD_B_BUTTON_TEXT + "\" button.";
        }


        newTextArea = new TextArea();
        newTextArea.setText( initialText );
        newTextArea.addClickHandler( new ClickHandler() {
            public void onClick( ClickEvent clickEvent ) {
                // If the text is still the original text, then clear it.
                if ( newTextArea.getText().equals( initialText ) ) {
                    newTextArea.setText( "" );
                }

            }
        });
    }
}

【问题讨论】:

  • 如果是这样,那么您将无法在第二个声明中覆盖 initialText,因为它是最终声明。

标签: java string class gwt compiler-errors


【解决方案1】:

initialText 不可解析,因为它不在给定的代码块范围内。

要解决此问题,请在 if/else 语句之前声明 intitalText,如下所示:

protected TextArea getNewTextArea() {
    if ( newTextArea == null ) {

        final String initialText;
        if (isItA){
            initialText = "Please paste valid text A here, and then
            press" + "the \"" + Labels.ADD_A_BUTTON_TEXT + "\" button.";

        }else{
            initialText = "Please paste valid text B here, and then press " + "the \"" + Labels.ADD_B_BUTTON_TEXT + "\" button.";
        }


        newTextArea = new TextArea();
        newTextArea.setText( initialText );
        newTextArea.addClickHandler( new ClickHandler() {
            public void onClick( ClickEvent clickEvent ) {
                // If the text is still the original text, then clear it.
                if ( newTextArea.getText().equals( initialText ) ) {
                    newTextArea.setText( "" );
                }

            }
        } );
    }

【讨论】:

  • 有没有办法做到这一点,所以我可以把它保留为'final String initialText;'?只是我想让该字符串在 if/else 代码块之后不被修改。
  • initialText(它的定义方式)可能是最终的。我已经用这个更新了答案。
【解决方案2】:

因为您的 final String initialTextif-else 块的本地对象。所以,在 if-else 块之外声明它,然后在其中初始化。

【讨论】:

    【解决方案3】:

    initialText 只存在于 curlies 块内。

    【讨论】:

      【解决方案4】:

      您需要将initialText移动到功能块开头的正下方

      受保护的文本区域 getNewTextArea() {

                  String initialText ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-29
        • 2020-01-12
        • 2014-11-11
        • 1970-01-01
        相关资源
        最近更新 更多