Java:带有自包含计数器的while循环

Phu*_* Le 0 java counter loops while-loop

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

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

for (int i = 0; i < 10; i++) {
    //do something
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

我想问的是:有没有办法将计数器变量放在while循环本身中,例如:

while ( (int i = 0) < 10 ) {
    counter++;
}
Run Code Online (Sandbox Code Playgroud)

And*_*ner 7

你可以在{and}周围放置int counterandwhile循环。

{
  int counter = 0;
  while (counter < 10) {
    counter++;
  }
}
// counter is inaccessible here
Run Code Online (Sandbox Code Playgroud)

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