这个问题有很多问题,您的问题对于您在谈论哪个问题含糊不清。所以我会在这里列出所有这些。
- 您将
NumberToGuess
and声明Answer
为 Integer 并将其分配给InputBox
. 但InputBox
可以返回任何东西(数字或字母)。一旦您尝试将用户的输入分配给NumberToGuess
. 那是在你检查它是否是数字之前。
- 如果有
OPTION STRICT ON
,它会显示编译错误“Option Strict On 不允许从 'String' 到 'Integer' 的隐式转换”。一般来说,保留OPTION STRICT ON
是一种很好的做法,有助于避免看似无辜的错误。例如,在这里您将String
类型分配给Integer
变量,这是不允许的。
- 您已经使用了
While
带有InputBox
. 除非他们给出正确的答案,否则用户无法取消游戏。InputBox 的取消按钮不起作用。
If
无论之前的条件如何,都将评估您的所有条件。我假设您希望一次只显示一个消息框。所以你可能也想利用ElseIf
。
为了解决这些问题,我们开始:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NumberToGuess As String '<-- declare as string because we will hold the result of InputBox in it.
Dim Answer As String = "" '<-- declare as string because we will hold the result of InputBox in it.
NumberToGuess = InputBox("Enter a Secret Number Between 1 and 20!")
While Answer <> NumberToGuess
Answer = InputBox("Please enter your guess")
If String.IsNullOrEmpty(Answer) Then Exit While '<-- if user pressed cancel button in InputBox.
If Not IsNumeric(Answer) Then
MsgBox("That ain't no number")
ElseIf CInt(Answer) > CInt(NumberToGuess) Then
MsgBox("Too high thicko. Try Again")
ElseIf CInt(Answer) < CInt(NumberToGuess) Then
MsgBox("Too Low chump. Try Again")
Else
' neither less nor more. so this is the correct answer.
MsgBox("Well done you guessed the right number")
Exit While
End If
End While
End Sub
然而,上面的代码是一个很大的烦恼,因为 a MessageBox
,然后InputBox, then
MessageBox , then
InputBox... 要解决这个问题,您可以在其InputBox
本身中显示消息。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NumberToGuess As String '<-- declare as string because we will hold the result of InputBox in it.
Dim Answer As String = "" '<-- replace with whatever answer you are expecting.
Dim Message As String = "Please enter your guess"
NumberToGuess = InputBox("Enter a Secret Number Between 1 and 20!")
While Answer <> NumberToGuess
Answer = InputBox(Message)
If String.IsNullOrEmpty(Answer) Then Exit While '<-- if user pressed cancel button in InputBox.
If Not IsNumeric(Answer) Then
Message = "That ain't no number"
ElseIf CInt(Answer) > CInt(NumberToGuess) Then
Message = "Too high thicko. Try Again"
ElseIf CInt(Answer) < CInt(NumberToGuess) Then
Message = "Too Low chump. Try Again"
Else
' neither less nor more. so this is the correct answer.
MsgBox("Well done you guessed the right number")
Exit While
End If
End While
End Sub