在java的for循环之外打印我的值 [英] Print the value of i outside the for loop in java
问题描述
我试图打印/获取循环变量i的值,并在for循环之外的另一个方法中使用它。如何做到这一点?
public void mousePressed(){
$ p
for(int i = 0; i< 1000; i ++){
boxes [i] .openIt();
$ / code $ / pre
解决方案变量在
中为
语句声明只在中为
组件和下面的代码块,见 JLS section 14.14.1.1 ,in (ForInit; Expression; ForUpdate)语句
$ p
lockquote
如果ForInit代码是一个局部变量声明,它将作为
执行,如果它是一个局部变量声明语句(§14.4 )出现在
a块中。
如果你希望在
之外有 code>,你必须在你想要访问的位置激活的范围内声明它;例如就在
之外循环:
int i;
for(i = 0; i <1000; ++ i)
;
//我可以在这个范围内访问
System.out.println(i);
另外,如果更合适,可以声明一个单独的变量并存储感兴趣的值它:
int k = ...;
for(int i = 0; i <1000; ++ i)
if(condition)//例如
k = i;
// k在这个范围内是可以访问的,我不是
System.out.println(k);
有关简要概述,请参阅这个页面,特别是最后的 Loop Scope 例子,它有一个和你的问题完全一样的例子。 / p>
I am trying to print/get the value of loop variable i and use it in another method outside the for loop. How do I do that?
public void mousePressed() { for (int i = 0; i < 1000; i++){ boxes[i].openIt(); } }
解决方案Variables declared in the
for
statement are in scope only in thefor
components and the following code block, see JLS section 14.14.1.1, in particular:for ( ForInit ; Expression ; ForUpdate ) Statement
If the ForInit code is a local variable declaration, it is executed as if it were a local variable declaration statement (§14.4) appearing in a block.
If you want to have it available outside the
for
, you have to declare it in a scope that is active in the location you want to access it; e.g. just outside thefor
loop:int i; for (i = 0; i < 1000; ++ i) ; // i is accessible in this scope System.out.println(i);
Alternatively, if it is more appropriate, you could declare a separate variable and store the value of interest in it:
int k = ...; for (int i = 0; i < 1000; ++ i) if (condition) // for example k = i; // k is accessible in this scope, i is not System.out.println(k);
For a brief summary see this page, specifically the Loop Scope example at the end, which has an example that is exactly like your question.
这篇关于在java的for循环之外打印我的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!