Java while 循环变量从外部访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5611395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java while loop variable accessing from outside
提问by weardstuff
How to access variable that is in the while loop from outside it ?
如何从外部访问while循环中的变量?
回答by Synesso
Always declare variables at the scope that makes sense. If your variable is to be referenced both inside and outside a loop, then it must be declared outside the loop.
始终在有意义的范围内声明变量。如果要在循环内部和外部都引用您的变量,则必须在循环外部声明它。
public String doIt() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++) {
builder.append("ponies ");
}
return builder.toString();
}
It is good practice to narrow the scope of variables so that they are only visible where they are needed.
缩小变量的范围以便它们仅在需要的地方可见是一种很好的做法。
回答by Sean Patrick Floyd
a) don't. it's a bad idea
a) 不要。这是个坏主意
b) Define it outside the loop
b) 在循环外定义它
int x;
while(something){
x = somethingElse;
}
回答by z7sg ?
Declare the variable outside the loop.
在循环外声明变量。