让我们看下面的代码片段:
int i = 0;
while ( i <= 10 )
{
System.out.println(i);
if ( i == 8 )
{
continue;
}
i++;
}
我必须在代码中进行哪些更改才能避免无限循环?
最佳答案
在开头而不是结尾处进行增量:
int i = -1;
while ( i <= 10 )
{
i++;
System.out.println(i);
if ( i == 8 )
{
continue;
}
// Presumably there would be some code here, or this doesn't really make much sense
}
或者,根据语言的不同,您可以在 while
语句中正确执行此操作(无论选择 i++
还是 ++,请记住运算符优先级我
)
int i = 0
while ( i++ <= 10 )
{
System.out.println(i);
if ( i == 8 )
{
continue;
}
// Presumably there would be some code here, or this doesn't really make much sense
}
不过,我对这种结构使用 while
循环表示质疑。如果您想在循环中使用计数器,for
循环通常更合适。
关于c# - 如何在 while 循环中使用 continue 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14386679/