简体   繁体   English

Java输出变量范围问题

[英]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? 有人可以快速概述一下为什么在打印Java时为什么输出“找不到符号”吗? 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. 除了在方法中定义的局部变量之外,我们还具有在块中定义的变量,例如if块和else块。 The scope in this case is constrained by the block itself. 这种情况下的范围受块本身的约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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