以下代码得到上述错误,我不明白为什么。我知道mod运算符需要前面和后面的数字,所以chrArray(i)没有得到数字。任何帮助表示感谢。
Public Class Form1
Private Sub Button3_Click(sender As Object, e As EventArgs)
Application.Exit()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs)
Textbox1.Text = ""
Textbox2.Text = ""
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs)
Dim sNumber As String
sNumber = TextBox1.Text
Textbox2.Text = EvenDigitMessage(sNumber)
End Sub
Private Function IsOnlyNumber(ByVal qty As String) As Boolean
Dim objRegExp As New System.Text.RegularExpressions.Regex("^\d+$")
Return objRegExp.Match(qty).Success
End Function
Private Function IsThreeDigitNumber(ByVal num As String) As Boolean
Dim objRegExp As New System.Text.RegularExpressions.Regex("^\d{3}$")
Return objRegExp.Match(num).Success
End Function
Private Function EvenDigitMessage(ByVal sNumber As String) As String
Dim bValidDigits As Boolean
Dim bValidNumber As Boolean
Dim sMessage As String
Dim iTotalEven As Integer = 0
If Not IsNumeric(sNumber) Then
sMessage = "Please enter a 3 digit number"
Else
bValidNumber = IsOnlyNumber(sNumber)
bValidDigits = IsThreeDigitNumber(sNumber)
If bValidNumber = False Or bValidDigits = False Then
sMessage = "Please enter a 3 digit number"
Else
iTotalEven = CountEvenDigits(sNumber)
sMessage = "This number contains" & iTotalEven & "even digits."
End If
End If
Return sMessage
End Function
Private Function CountEvenDigits(ByVal sNumber As String) As Integer
Dim i As Integer
Dim chrArray() As Char
Dim iTotal As Integer = 0
chrArray = sNumber.ToCharArray
For i = 0 To chrArray.Length - 1
If chrArray(i) Mod 2 = 0 Then
If iTotal = 0 Then
iTotal = 1
Else
iTotal = iTotal + 1
End If
End If
Next
Return iTotal
End Function
结束班
答案 0 :(得分:1)
基于这个linke https://msdn.microsoft.com/en-us/library/7sx7t66b.aspx
Visual Basic不直接在Char和数字类型之间转换。您可以使用Asc或AscW函数将Char值转换为表示其代码点的Integer。您可以使用Chr或ChrW函数将Integer值转换为具有该代码点的Char。 如果启用了类型检查开关(Option Strict Statement),则必须将文字类型字符附加到单字符字符串文字以将其标识为Char数据类型。以下示例说明了这一点。
所以你必须将你的代码更改为像这样的东西
If Asc(chrArray(i)) Mod 2 = 0 Then
If iTotal = 0 Then
iTotal = 1
Else
iTotal = iTotal + 1
End If
End If