c# - 如何在 while 循环中使用 continue 语句?

标签 c# java while-loop continue

让我们看下面的代码片段:

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/

相关文章:

shell - 如何循环脚本直到用户输入为空?

c# - 如何在 Asp.net MVC 中编写 OAuth2 Web API 客户端

c# - 为什么 Request.QueryString ["path"] 将所有 + 号转换为空格?

c# - 如何使用c#实现非二叉树结构

java - EasyMock expect 的使用方法

bash - 如何在bash中对浮点变量求和?

c# - 查找字符串中的第一个字母字符

java - PACT 用于 JSON 整数数组

java - Solr/Lucene : Is it possible to overload a method in a Custom Similarity Class?

Java while循环永远不会进入循环