Java-从外部访问在循环内部声明的变量 [英] Java - accessing variable declared inside loop from outside of it

查看:70
本文介绍了Java-从外部访问在循环内部声明的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to make a variable that is declared inside a loop be able to be called from outside that for loop?

推荐答案

如果在循环完成时需要该对象,则需要创建对该对象的引用,该引用在循环结束后仍然存在.这样吧

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
    }
}

最后,为什么不放弃作用域并在循环内使用obj?

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
}

这篇关于Java-从外部访问在循环内部声明的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆