條件判斷敘述
依據運算式的值,有條件的執行一組陳述式。
IF使用方法一、
If Then條件敘述是一種是否執行的條件,決定是否執行區塊內的程式碼。如果If條件為True,就執行Then/End If間的程式碼,其語法如下所示:
1: If 條件 Then
2: 程式區塊
3: End If
例如:學生成績超過60分是及格分數,如下所示:
1: If txtScore.Text >= 60 Then
2: lblOutput.Text &= "成績在範圍中.." & vbNewLine
3: lblOutput.Text &= "學生成績及格: " & txtScore.Text & vbNewLine
4: End If
範例練習
1: Sub Main()
2:
3: Dim score As Integer=100
4: Dim result As String
5:
6: Console.Write("分數:"&score)
7:
8: '判斷score有沒有大於
9: If score>=60 Then
10: result="及格!"
11: Else
12: result="不及格!"
13: EndIf
14: Console.WriteLine(result)
15: Console.ReadKey()
16:
17: End Sub
IF使用方法二、
我們可以加上Else關鍵字,如果If條件為True,就執行Then/Else間的程式碼;False就執行Else/End If間的程式碼,其語法如下所示:
1: If 條件 Then
2: 程式區塊1
3: Else
4: 程式區塊2
5: End If
例如:使用If Then/Else條件敘述,以身高來決定購買半票或全票,如下所示:
1: length = CInt(txtLength.Text)
2: If length > 120 Then
3: lblOutput.ForeColor = Color.Blue
4: lblOutput.Text = "購買全票!"
5: Else
6: lblOutput.ForeColor = Color.Red
7: lblOutput.Text = "購買半票!"
8: End If
IF使用方法三、
If Then/ElseIf條件敘述是If Then/Else條件敘述的延伸,使用ElseIf來重複建立多選一條件敘述。
例如:四則運算的If Then/ElseIf條件敘述,如下所示:
1: If rdbAdd.Checked = True Then
2: result = opd1 + opd2 ' 加
3: ElseIf rdbSubtract.Checked = True Then
4: result = opd1 - opd2 ' 減
5: ElseIf rdbMultiply.Checked = True Then
6: result = opd1 * opd2 ' 乘
7: ElseIf rdbDivide.Checked = True Then
8: result = opd1 / opd2 ' 除
9: Else
10: MsgBox("錯誤: 沒有選擇運算子!")
11: End If