简体   繁体   English

访问for循环之外的整数

[英]Accessing an integer outside its for loop

for (int x = 1; x <= 3; x++) {
  System.out.println("Number: " + x);
}
System.out.println("Done! Counted to: " + x);

This gives an error, suggesting to me that I can't access the variable outside the for loop. 这给出了一个错误,告诉我我无法访问for循环之外的变量。
Is there a way to do so? 有办法吗?

Declare it outside of the for statement, then omit the first part of the for statement. 声明它之外for语句,则忽略的第一部分for语句。

int x = 1;
for (; x <= 3; x++) {
    System.out.println("Number: " + x);
}

System.out.println("Done! Counted to: " + x);

Hint : You can omit any of the three parts of the for loop. 提示 :您可以省略for循环的三个部分中的任何一个。 For example, you might wish to omit the last part if you wish to do some conditional incrementing inside of the compound statement that makes up your for loop. 例如,如果您希望在构成for循环的复合语句中进行一些条件递增,则可能希望省略最后一部分。

int x = 1;
for (; x <= 3;) {
    if (x % 2 == 0) {
        x += 2;
    } else {
        x++;
    }
}

Becareful with this kind of thing though. 尽管如此,还是很喜欢这种东西。 It's easy to find yourself in an infinite loop if you aren't careful. 如果你不小心,很容易发现自己陷入无限循环。

Put x outside loop and use other variable for loop. x外部循环放入并使用其他变量进行循环。

Code

int x = 0;
for (int i = 1; i <= 3; i++) {
    System.out.println("Number: " + i);
    x = i;
}
System.out.println("Done! Counted to: " + x);

Result 结果

Number: 1
Number: 2
Number: 3
Done! Counted to: 3

Yes, very easily. 是的,非常容易。 Just do it like this: 就这样做:

int x = 0;
for (x=1; x<=3; x++) {
    System.out.println("Number: " +x);
}

System.out.println("Done! Counted to: "+x);

You don't have to declare a new variable in the loop, you can use an existing one if you want to. 不必申报的循环一个新的变量,你可以使用现有的一个,如果你想。

When you declare a variable inside for loop, the scope of that variable is only within a loop. 在for循环中声明变量时,该变量的范围仅在循环内。

In order to access that variable outside for loop, declare it outside. 为了在for循环外访问该变量,请在外部声明它。

int x =0;
for (x=1; x<=3; x++) {
    System.out.println("Number: " +x);
    }
    System.out.println("Done! Counted to: "+x);
    }
}

If the first part is useless, might as well use a while loop then. 如果第一部分没用,那么不妨使用while循环。

int x = 1;

while (x <= 3)  
{         
    System.out.println("Number: " + x);        
    x++;   
}  

System.out.println("Done! Counted to: "+ x);
 
int x=1;
for (; x<=3; x++) {
  System.out.println("Number: " +x);
}
System.out.println("Done! Counted to: "+x);

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

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