Visual Basic If…Then…Else 语句

If 语句可以跟随一个可选的 Else 语句,当布尔表达式为 false 时执行该语句。


语法

VB 中的 If…Then…Else 语句的语法如下:

  1. If(boolean_expression)Then
  2. '当 boolean_expression 为 true,则执行这里的语句
  3. Else
  4. ' boolean_expression false,则执行这里的语句
  5. End If

如果布尔表达式的计算结果为 true,则将执行 if 代码块,否则将执行代码块。


流程图


实例

  1. Module decisions
  2. Sub Main()
  3. 'local variable definition '
  4. Dim a As Integer = 100
  5. ' check the boolean condition using if statement '
  6. If (a < 20) Then
  7. ' if condition is true then print the following '
  8. Console.WriteLine("a is less than 20")
  9. Else
  10. ' if condition is false then print the following '
  11. Console.WriteLine("a is not less than 20")
  12. End If
  13. Console.WriteLine("value of a is : {0}", a)
  14. Console.ReadLine()
  15. End Sub
  16. End Module

结果如下:

  1. a is not less than 20
  2. value of a is : 100

If…Else If…Else 语句

If 语句后面可以跟一个可选的 Else if…Else 语句,这对使用单个 If…Else If 语句判断各种条件非常有用。

当使用 If…Else If…Else 语句时,有几点要注意。

  • 一个 If 可以有零个或一个 Else,它必须在一个 Else If 之后。
  • 一个如果可以有零到许多 Else If,但它们必须在 Else 之前。
  • 当有一个 Else if 成功,其余 Else IfElse 将不会再进行判断执行。

语法

VB 中的 if…else if…else 语句的语法如下:

  1. If(boolean_expression 1)Then
  2. ' 当 boolean_expression 1 为 true 时执行
  3. ElseIf( boolean_expression 2)Then
  4. ' boolean_expression 2 true 时执行
  5. ElseIf( boolean_expression 3)Then
  6. ' 当 boolean_expression 3 为 true 时执行
  7. Else
  8. ' 当上面的表达式都不为 true 时执行
  9. End If

实例

  1. Module decisions
  2. Sub Main()
  3. 'local variable definition '
  4. Dim a As Integer = 100
  5. ' check the boolean condition '
  6. If (a = 10) Then
  7. ' if condition is true then print the following '
  8. Console.WriteLine("Value of a is 10") '
  9. ElseIf (a = 20) Then
  10. 'if else if condition is true '
  11. Console.WriteLine("Value of a is 20") '
  12. ElseIf (a = 30) Then
  13. 'if else if condition is true
  14. Console.WriteLine("Value of a is 30")
  15. Else
  16. 'if none of the conditions is true
  17. Console.WriteLine("None of the values is matching")
  18. End If
  19. Console.WriteLine("Exact value of a is: {0}", a)
  20. Console.ReadLine()
  21. End Sub
  22. End Module

结果如下:

  1. None of the values is matching
  2. Exact value of a is: 100

分类导航