Elliott Hawkins Elliott Hawkins - 26 days ago 4
Vb.net Question

'ElseIf' must be preceded by a matching 'If' or 'Elsif'

Hi I am currently coding a blackjack game for a school project. But I have encountered an error. When I run my program the code says 'ElseIf' must be preceded by a matching 'If' or "ElsIf'. I have tried lots of different arrangements but I cannot figure it out. Below is my code for the Msgbox.

Please Help

Dim responseYouWon = MsgBox(youWonMsg, style, youWonTitle)
Dim responseYouLost = MsgBox(youLostMsg, style, youLostTitle)
Dim responseYouDrew = MsgBox(youDrewMsg, style, youDrewTitle)

If PlayerSum < 21 And PlayerSum > ComputerSum Then
If responseYouWon = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If
End If

ElseIf ComputerSum > 21 And PlayerSum < 21 Then
If responseYouWon = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

ElseIf ComputerSum > 21 And ComputerSum < 21 Then
If responseYouWon = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

ElseIf PlayerSum = 21 And ComputerSum > 21 Then
If responseYouWon = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

ElseIf PlayerSum = 21 And ComputerSum < 21 Then
If responseYouWon = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

ElseIf ComputerSum < 21 And ComputerSum > PlayerSum Then
If responseYouLost = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

ElseIf PlayerSum > 21 And ComputerSum < 21 Then
If responseYouLost = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

ElseIf ComputerSum = 21 And PlayerSum <> 21 Then
If responseYouLost = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

ElseIf ComputerSum = PlayerSum Then
If responseYouDrew = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

ElseIf PlayerSum > 21 And ComputerSum > 21 Then
If responseYouDrew = MsgBoxResult.Yes Then
btnPlayAgain.PerformClick()
Else
btnQuit.PerformClick()
End If

End Sub

Answer

You can make this way easier on yourself:

If PlayerSum > 21 Then PlayerSum = 0
If ComputerSum > 21 Then ComputerSum = 0

Dim response As MsgBoxResult
If PlayerSum > ComputerSum Then
    response = MsgBox(youWonMsg, style, youWonTitle)
ElseIf ComputerSum > PlayerSum Then
    response = MsgBox(youLostMsg, style, youLostTitle)
Else
    response = MsgBox(youDrewMsg, style, youDrewTitle)
End If

If response = MsgBoxResult.Yes Then
    btnPlayAgain.PerformClick()
Else
    btnQuit.PerformClick()
End If

But to your original code... look at the extra End If closing statement on line 11.