当我在输入框中输入字母字符或将输入框留空时,我的程序崩溃了。为什么我的验证if语句不起作用?
Option Strict On
Public Class frmPickUpSticks
Dim playersTurn As Boolean = False
Dim remainingSticks As Integer 'count sticks
Dim losses As Integer = 0 'count player losses
Private Sub btnNewGame_Click(sender As Object, e As EventArgs) Handles btnNewGame.Click
lblOutput.Text = ""
remainingSticks = CInt(InputBox("How many matchsticks would you like (5 - 25)?", "Pick Number of Matches!"))
'Validate input
If IsNumeric(remainingSticks) Then
If (remainingSticks >= 5) And (remainingSticks <= 25) Then
DisplayMatches()
If (remainingSticks Mod 4 = 1) Then
MessageBox.Show("You go first!")
playersTurn = True
turns()
Else
MessageBox.Show("I go first.")
turns()
End If
Else
MessageBox.Show("Please enter a number between 5 and 25.")
End If
Else
MessageBox.Show("Input must be numeric.", "Input Error")
End If
答案 0 :(得分:0)
您无法自动获取用户在InputBox中键入的内容,并将此输入传递给任何需要输入数字的函数或方法。 InputBox方法被设计为返回一个字符串,并且需要转换此字符串,但您需要使用知道如何解析字符串的方法。否则,非设计用于处理非数字值(CInt)的方法将导致异常。
相反,你应该尝试某种解析,NET Library提供了许多工具。在您的情况下,正确的是Int32.TryParse
Dim remainingSticks As Integer
Dim userInput = InputBox("How many matchsticks .....")
If Int32.TryParse(userInput, remainingSticks) Then
.... ok your remainingStick contains the converted value
Else
MessageBox.Show("You should type a valid integer number between 5-25")
Int32.TryParse将查看您的输入字符串并尝试转换为有效的整数值。如果成功则第二个参数包含转换后的整数并返回True,如果失败则返回false,第二个参数的默认值为零。
当然,在成功转换为整数后,您不再需要使用IsNumeric检查
答案 1 :(得分:0)
您应该在inputbox中使用字符串变量
dim st as string
st = InputBox(“你想要多少个火柴棍(5 - 25)?”,“选择匹配数量!”))
remainingSticks = val(st)
。 。