简体   繁体   中英

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?

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

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