我必须为项目创建一个蛇和梯子游戏。我的电路板上有30个空格。如果标记超过30,则应用程序崩溃:
“appCounter.exe中发生了'System.NullReferenceException'类型的未处理异常
附加信息:对象引用未设置为对象的实例。“
如果滚动的数字超过30,我希望标记保持原样。
这是我的代码:
Public Class frmBoard
Dim intScore As Integer
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
'declartions
Dim intValue As Integer
Dim strCounterName As String
Dim roll As New Random()
Dim intRoll = roll.Next(1, 7)
'make the current counter visible
If intScore > 0 Then
strCounterName = "lblCounter" & intScore
Me.Controls(strCounterName).Visible = False
End If
'input
intValue = intRoll
intScore = intScore + intValue
strCounterName = "lblcounter" & intScore.ToString
'output
txtMove.Text = intRoll
Me.Controls(strCounterName).Visible = True
If intScore = 3 Then
lblCounter3.Visible = False
lblCounter22.Visible = True
intScore = 22
End If
If intScore = 5 Then
lblCounter5.Visible = False
lblCounter8.Visible = True
intScore = 8
End If
If intScore = 11 Then
lblCounter11.Visible = False
lblCounter26.Visible = True
intScore = 26
End If
If intScore = 20 Then
lblCounter20.Visible = False
lblCounter29.Visible = True
intScore = 29
End If
If intScore = 17 Then
lblCounter17.Visible = False
lblCounter4.Visible = True
intScore = 4
End If
If intScore = 19 Then
lblCounter19.Visible = False
lblCounter7.Visible = True
intScore = 7
End If
If intScore = 21 Then
lblCounter21.Visible = False
lblCounter9.Visible = True
intScore = 9
End If
If intScore = 27 Then
lblCounter27.Visible = False
lblCounter1.Visible = True
intScore = 1
End If
If intScore = 31 Then
lblCounter31.Visible = False
lblCounter1.Visible = True
intScore = 1
End If
If intScore = 32 Then
lblCounter32.Visible = False
lblCounter1.Visible = True
intScore = 1
End If
If intScore = 33 Then
lblCounter33.Visible = False
lblCounter1.Visible = True
intScore = 1
End If
If intScore = 30 Then
MsgBox("Winner")
End If
If intScore > 30 Then
MsgBox("OvErBoArD")
End If
End Sub
End Class
答案 0 :(得分:0)
这将向您的用户显示他们已经过去并跳过将总计添加到总数中以使其保留到位。
变化:
'input
intValue = intRoll
intScore = intScore + intValue
strCounterName = "lblcounter" & intScore.ToString
要:
'input
intValue = intRoll
If intScore + intValue > 30 Then
MsgBox "OvErBoArD"
Else
intScore = intScore + intValue
End If
strCounterName = "lblcounter" & intScore.ToString
答案 1 :(得分:-2)
由于当intScore超过30时只有30个计数器,因此会抛出此异常。
在输入中添加If语句,如下所示:
'input
intValue = intRoll
If intscore + intvalue < 30 then
intscore=intscore + intvalue
End if
strCounterName = "lblcounter" & intScore.ToString
这样它在设置lblcounter之前不会超过30,并且不会出错