gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:13:11 25 4
gpt4 key购买 nike

我想问是否有什么方法可以在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 计数器while 循环周围。

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

但这确实比仅使用 for 循环要困惑得多。

关于Java:带有独立计数器的while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40775780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com