Vb.net-if-else-statements
提供:Dev Guides
VB.Net-If … Then … Elseステートメント
*If* ステートメントの後にオプションの *Else* ステートメントを続けることができます。これは、ブール式がfalseの場合に実行されます。
構文
If … Then …の構文 VB.Netのその他のステートメントは次のとおりです-
If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If
ブール式が true と評価されると、コードブロックのifブロックが実行され、そうでない場合はコードブロックが実行されます。
流れ図
例
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
' check the boolean condition using if statement
If (a < 20) Then
' if condition is true then print the following
Console.WriteLine("a is less than 20")
Else
' if condition is false then print the following
Console.WriteLine("a is not less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
上記のコードをコンパイルして実行すると、次の結果が生成されます-
a is not less than 20
value of a is : 100
If … Else If … Elseステートメント
*If* ステートメントの後にオプションの *Else if ... Else* ステートメントを続けることができます。これは、単一のIf ... Else Ifステートメントを使用してさまざまな条件をテストするのに非常に便利です。
If …を使用する場合 その他の場合… それ以外の場合、留意すべき点はほとんどありません。
- IfはElseを0個または1個持つことができ、Else Ifの後に来る必要があります。
- Ifは0個以上のElse Ifを持つことができ、Elseの前に来る必要があります。
- Else ifが成功すると、残りのElse IfまたはElseはテストされません。
構文
VB.Netのif … else if … elseステートメントの構文は次のとおりです-
If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the boolean expression 3 is true
Else
' executes when the none of the above condition is true
End If
例
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
' check the boolean condition '
If (a = 10) Then
' if condition is true then print the following '
Console.WriteLine("Value of a is 10") '
ElseIf (a = 20) Then
'if else if condition is true '
Console.WriteLine("Value of a is 20") '
ElseIf (a = 30) Then
'if else if condition is true
Console.WriteLine("Value of a is 30")
Else
'if none of the conditions is true
Console.WriteLine("None of the values is matching")
End If
Console.WriteLine("Exact value of a is: {0}", a)
Console.ReadLine()
End Sub
End Module
上記のコードをコンパイルして実行すると、次の結果が生成されます-
None of the values is matching
Exact value of a is: 100