Reputation: 175
the following code is getting the above error and i cant see why. i know the mod operator needs numbers in front and behind it so chrArray(i) is not getting a number. any help appreciated.
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
End Class
Upvotes: 0
Views: 576
Reputation: 61
Base on this linke https://msdn.microsoft.com/en-us/library/7sx7t66b.aspx
Visual Basic does not convert directly between Char and the numeric types. You can use the Asc or AscW function to convert a Char value to an Integer that represents its code point. You can use the Chr or ChrW function to convert an Integer value to a Char that has that code point. If the type checking switch (Option Strict Statement) is on, you must append the literal type character to a single-character string literal to identify it as the Char data type. The following example illustrates this.
so you have to change your code to somthing like this
If Asc(chrArray(i)) Mod 2 = 0 Then
If iTotal = 0 Then
iTotal = 1
Else
iTotal = iTotal + 1
End If
End If
Upvotes: 1