简体   繁体   English

Java-从外部访问在循环内部声明的变量

[英]Java - accessing variable declared inside loop from outside of it

有没有一种方法可以使在循环内部声明的变量能够从for循环外部调用?

If you need the object when the loop is finished, you need to create a reference to it that still exists after the loop is finished. 如果在循环结束时需要该对象,则需要创建对该对象的引用,该引用在循环结束后仍然存在。 So do this 这样吧

Object pointer = null;
for (int v = 0; v < n; v++) {
    ...
    pointer = myObj;
}

// use pointer here

If you don't want that object sticking around after you are done with it, say you need to only use it for one thing after the loop, then you can create it in it's own scope like this: 如果您不希望该对象在完成后留下来,说您只需要在循环后将其用于一件事情,则可以在自己的作用域中创建它,如下所示:

{
    Object pointer = null;
    for (int v = 0; v < n; v++) {
        ...
        pointer = myObj;
    }

    // use pointer here
}
// pointer no longer exists here

Following this logic, you can even create the scope inside the loop itself 按照此逻辑,您甚至可以在循环本身内部创建作用域

for (int v = 0; v < n; v++) {
    ...
    {
        // If loop is done, now use the myObj
    }
}

And finally, why not just get rid of the scope and use the obj inside the loop? 最后,为什么不放弃范围并在循环内使用obj?

for (int v = 0; v < n; v++) {
    ...
    // If loop is done, now use the myObj
}

If you create a variable in a loop (or any set of curly braces) its scope is only the body of that loop. 如果在循环(或花括号的任何集合)中创建变量,则其作用域仅是该循环的主体。 You would have to create the variable before hand and set it in the loop. 您必须先创建变量并将其设置在循环中。

在块内声明的变量不能在该块外访问,它们的作用域和生存期仅限于该块,但是对于在块外声明的变量,其值可以在该块内更改,并且该值将被一次反映为了更好的理解,您可以通过以下链接http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm

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

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