0

在编写猜谜游戏时,我遇到了一个看似无法解决的大问题。我在线上遇到异常错误:

MessageLabel.Text = Message.ToString

这是代码:

Option Strict On

Public Class ABabyGuess

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim randomGenerator As New Random
        Dim secretNumber As Integer
        Const NUMBER_MIN As Integer = 1
        Const NUMBER_MAX As Integer = 200
        Dim guessNumber As Integer
        Dim Won As Boolean = False
        Dim Message As String = ""
        Dim MAX_TRIES As Integer = 500
        Dim CurrentTrys As Integer
        secretNumber = randomGenerator.Next(NUMBER_MIN, NUMBER_MAX)
        Try
            Do While CurrentTrys <= MAX_TRIES And Not Won
                CurrentTrys = CurrentTrys + 1
                ABaby.ATryTableLabel.Text = ""
                guessNumber = Integer.Parse(GuessTextBox.Text)
                If guessNumber > secretNumber Then
                    Message = Message & guessNumber.ToString & "Too Big" & Environment.NewLine
                ElseIf guessNumber < secretNumber Then
                    Message = Message & guessNumber.ToString & "Too Small" & Environment.NewLine
                ElseIf guessNumber = secretNumber Then
                    Won = True
                End If
            Loop
        Catch ex As Exception
            If guessNumber > 100 Then
                MessageBox.Show("Please inut a number below 100.")
            ElseIf guessNumber = 0 Then
                MessageBox.Show("Please input a number above 0")
            End If
        End Try
            If Message.ToString IsNot Nothing Then
                ABaby.ATryLabel.Text = Message.ToString
            End If
        If Won = True Then
            MessageBox.Show("congratulations! You Won!", "congratulations", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        ElseIf Won = False And CurrentTrys = 7 Then
            MessageBox.Show("...You actually lost. I give up...", "...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub
End Class

错误在于NullReferenceException was Unhandled细节说:{"Object variable or With block variable not set."}老实说,我在互联网上找不到任何地方来解决这个问题。如果您想知道为什么我将表格命名为 ABaby,它是我的多难度项目中可用的最简单的难度级别。

4

1 回答 1

0

这是因为您没有初始化 MessageLabel 或 Message 或两者。

在调用或访问它们的方法/属性之前检查您的代码以查看它们是否已正确初始化。

于 2013-04-19T03:46:44.627 回答