简体   繁体   中英

Java Output Variable Scope Issue

I have an issue regarding variable scope in the following piece of code. Can someone give a quick overview as to why java "cannot find the symbol" for output when it is printed? Thanks.

class Main
{
    public static void main(String[] args) {
        String text = "hello";
        if (text.indexOf(" ") == -1) //if a space doesn't exist
        {
            String output = "one word";
        }
        else
        {
            String output = "more than one word";
        }
        System.out.println(output);
    }
}

变量output 仅存在于当前包含在if块和else块中的包含代码块中,如果要访问ifelse块之外的变量outputif需要在if之前定义它块。

Local variables

A local variable is the one that is declared within a method or a constructor (not in the header). The scope and lifetime are limited to the method itself.

In addition to the local variables defined in a method, we also have variables that are defined in blocks, eg the if block and an the else block. The scope in this case is constrained by the block itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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