当前位置:   article > 正文

.NET C#基础:While & do-while

.NET C#基础:While & do-while

介绍

do-while 和 while 语句通过重复代码块直到满足条件来控制代码执行流。

学习目标

  • 利用 do-while 循环循环循环访问代码块

  • 实现 while 循环以遍历代码块。

开发人员的先决条件

  • 熟悉使用语句。if

  • 熟练使用和迭代语句。foreach for

  • 写作表达的能力。Boolean

  • 使用类和方法生成随机数的知识。System.RandomRandom.Next()

开始

什么是do-while循环?

只要指定的布尔表达式保持 true,do-while 语句就会运行语句或语句块。由于此表达式在每次循环执行后计算,因此 do-while 循环至少执行一次。

示例:do-while

让我们创建连续生成从 1 到 10 的随机数的代码,直到生成数字 7。数字 7 可以在一次迭代中生成,也可以在多次迭代后生成。

首先,在控制台应用程序中创建一个名为“”的静态类文件。将提供的代码片段插入到此文件中。WhileLoop.cs

  1. /// <summary>
  2. /// Outputs
  3. /// 2
  4. /// 5
  5. /// 8
  6. /// 2
  7. /// 7
  8. /// </summary>
  9. public static void DoWhileLoopExample()
  10. {
  11. Random random = new Random();
  12. int current = 0;
  13. do
  14. {
  15. current = random.Next(1, 11);
  16. Console.WriteLine(current);
  17. } while (current != 7);
  18. }

从 main 方法执行代码,如下所示

  1. #region Day 5 - While & do-while
  2. WhileLoop.DoWhileLoopExample();
  3. #endregion

控制台输出

  1. 2
  2. 5
  3. 8
  4. 2
  5. 7

示例:while

该语句将基于布尔表达式进行迭代。为此,请将另一个方法添加到同一个静态类中,如下所示while

  1. /// <summary>
  2. /// Outputs
  3. /// 9
  4. /// 7
  5. /// 5
  6. /// Last number: 1
  7. /// </summary>
  8. public static void WhileLoopExample()
  9. {
  10. Random random = new Random();
  11. int current = random.Next(1, 11);
  12. while (current >= 3)
  13. {
  14. Console.WriteLine(current);
  15. current = random.Next(1, 11);
  16. }
  17. Console.WriteLine($"Last number: {current}");
  18. }

从 main 方法执行代码,如下所示

  1. #region Day 5 - While & do-while
  2. WhileLoop.WhileLoopExample();
  3. #endregion

控制台输出

  1. 9
  2. 7
  3. 5
  4. Last number: 1

使用 do-while 继续语句

有时,开发人员需要跳过代码块中的其余代码,然后继续进行下一次迭代。为此,请将另一个方法添加到同一静态类中,如下所示

  1. /// <summary>
  2. /// Outputs
  3. /// 5
  4. /// 1
  5. /// 6
  6. /// 7
  7. /// </summary>
  8. public static void ContinueDoWhileLoopExample()
  9. {
  10. Random random = new Random();
  11. int current = random.Next(1, 11);
  12. do
  13. {
  14. current = random.Next(1, 11);
  15. if (current >= 8) continue;
  16. Console.WriteLine(current);
  17. } while (current != 7);
  18. }

从 main 方法执行代码,如下所示

  1. #region Day 5 - While & do-while
  2. WhileLoop.ContinueDoWhileLoopExample();
  3. #endregion

控制台输出

  1. 5
  2. 1
  3. 6
  4. 7
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/743627
推荐阅读
相关标签
  

闽ICP备14008679号