Java:带有独立计数器的 while 循环

Java: while loop with self-contain counter

我想问一下有没有什么办法可以在Java中写一个while循环,循环里面也有主计数器,也就是说当你退出循环的时候,计数器变量会也被摧毁。

例如,当我们退出这个循环时:

for (int i = 0; i < 10; i++) {
    //do something
}

变量 i 也被销毁,从而保持代码干净。

但是对于while循环,我们必须在循环本身之外创建一个计数器变量;所以,当循环退出时,计数器变量仍然存在于主程序中。

int counter = 0;
while (counter < 10) {
     counter++;
}
counter--; //we can still manipulate the counter variable here

我想问的是:有没有办法把计数器变量放在while循环本身里面,比如:

while ( (int i = 0) < 10 ) {
    counter++;
}

您可以将 {} 放在 int counterwhile 循环周围。

{
  int counter = 0;
  while (counter < 10) {
    counter++;
  }
}
// counter is inaccessible here

但这确实比使用 for 循环要麻烦得多。

据我所知,你必须使用 "external" 计数器。