我正在编写一个简单的随机数猜测游戏,并使用语句isnumeric。这是在Visual Studio 2013中完成的Visual Basic程序。
这是我的代码:
Private Sub btnTry_Click(sender As Object, e As EventArgs) Handles btnTry.Click
Dim intTry As Integer
Dim strInputBox As String
strInputBox = InputBox("Enter Your Number to Guess.", "Input Needed")
If IsNumeric(strInputBox) Then
intTry = CInt(strInputBox)
lstTried.Items.Add(intTry)
Else
MessageBox.Show("Please Type Only Numbers")
End If
If intTry = intRandomNumber Then
MessageBox.Show("You Got It!", "Correct Guess")
Else
MessageBox.Show("Incorrect. Please try again.", "Incorrect Guess")
End If
我想用某些东西代替" IsNumeric"在我的If语句中。我根本不确定如何做到这一点。有人能帮我吗。我试图使用integer.tryparse但无法使其工作。特别的帮助将不胜感激。这个现在很有效,我很想不管它,但我被告知它的旧式代码,还有另一种方法可以做到。
谢谢,
史蒂夫
答案 0 :(得分:2)
你可以试试这个,我也对你的代码做了一些暗示性修改。
Private Sub btnTry_Click(sender As Object, e As EventArgs) Handles btnTry.Click
Dim intTry As Integer = 0
'This wont throw an exception if it's not an integer, it will come back false...
If Integer.TryParse(InputBox("Enter your number to guess.", "Input Needed"), intTry) Then
lstTried.Items.Add(intTry)
Else
MessageBox.Show("Please Type Only Numbers")
Exit Sub
End If
If intTry = intRandomNumber Then
MessageBox.Show("You Got It!", "Correct Guess")
Else
MessageBox.Show("Incorrect. Please try again.", "Incorrect Guess")
End If
End Sub