简体   繁体   English

如何从循环外部访问在嵌套循环中声明或初始化的数组或变量?

[英]How do you access an array or variable declared or initialized in a nested loop from outside of the loop?

How do you access an array or variable declared or initialized in a nested loop from outside of the loop?如何从循环外部访问在嵌套循环中声明或初始化的数组或变量?

You cannot.你不能。 You must declare the array outside the loop.您必须在循环外声明数组。 This may seem strange at first but what if the condition for the loop to run even once is never met?乍一看这似乎很奇怪,但如果循环运行一次的条件从未满足怎么办? How could you possibly then access an array which was never even created?那么你怎么可能访问一个从未创建过的数组呢?

You cannot.你不能。 Java uses block scope, so variables declared within any block (such as a loop) are not accessible from outside. Java 使用块 scope,因此无法从外部访问任何块(例如循环)内声明的变量。 You'll need to assign them to something that has an outer scope.您需要将它们分配给具有外部 scope 的对象。

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

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