Java while循环变量从外部访问 [英] Java while loop variable accessing from outside
本文介绍了Java while循环变量从外部访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从外部访问while循环中的变量?
How to access variable that is in the while loop from outside it ?
推荐答案
始终在有意义的范围内声明变量.如果要在循环内外都引用您的变量,则必须在循环外声明它.
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.
这篇关于Java while循环变量从外部访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文