Visual Basic Do 循环

当布尔条件为 True 时,或者直到条件变为 True 时,它将重复执行所包含的代码块。也可以随时用 Exit Do 语句终止。

Do 循环结构的语法是:

  1. Do { While | Until } condition
  2. [ statements ]
  3. [ Continue Do ]
  4. [ statements ]
  5. [ Exit Do ]
  6. [ statements ]
  7. Loop

或者

  1. Do
  2. [ statements ]
  3. [ Continue Do ]
  4. [ statements ]
  5. [ Exit Do ]
  6. [ statements ]
  7. Loop { While | Until } condition

流程图


实例

  1. Module loops
  2. Sub Main()
  3. ' local variable definition
  4. Dim a As Integer = 10
  5. 'do loop execution
  6. Do
  7. Console.WriteLine("value of a: {0}", a)
  8. a = a + 1
  9. Loop While (a < 20)
  10. Console.ReadLine()
  11. End Sub
  12. End Module

结果如下:

  1. value of a: 10
  2. value of a: 11
  3. value of a: 12
  4. value of a: 13
  5. value of a: 14
  6. value of a: 15
  7. value of a: 16
  8. value of a: 17
  9. value of a: 18
  10. value of a: 19

如果使用 Until 语句而不是 While 语句,那么程序的行为方式相同:

  1. Module loops
  2. Sub Main()
  3. ' local variable definition
  4. Dim a As Integer = 10
  5. 'do loop execution
  6. Do
  7. Console.WriteLine("value of a: {0}", a)
  8. a = a + 1
  9. Loop Until (a = 20)
  10. Console.ReadLine()
  11. End Sub
  12. End Module

结果如下:

  1. value of a: 10
  2. value of a: 11
  3. value of a: 12
  4. value of a: 13
  5. value of a: 14
  6. value of a: 15
  7. value of a: 16
  8. value of a: 17
  9. value of a: 18
  10. value of a: 19

分类导航