Identifying a function when reading in Visual Basic - vb.net

I'm having trouble idetifying what this does? my confusion relates to the "end for" does this mean the function would end the 'for' loop if the value is false?
example data in Array can [2,4,5] Val 3, Result would be false and end the loop or?
Thanks in advance.
Function YetToName (data As Integer(), val As Integer) As Boolean
Dim i As Integer
For i = 0 To data.Length - 1
If data(i) = val Then
Return True
End If
End For
Return False
End Function

The code snippet you have provided is not valid vb.net code.
"Exit For" is used to break out of a For-Next loop before the loop completes.
A For-Next Loop must, by definition, have a "Next" statement to be valid. The code could be rewritten as...
Function YetToName(data As Integer(), val As Integer) As Boolean
Dim i As Integer
Dim ReturnValue As Boolean = False
For i = 0 To data.Length - 1
If data(i) = val Then
ReturnValue = True
Exit For
End If
Next
Return ReturnValue
End Function

Related

What is the best way to check if bits in two bitArrays are identical?

I often need to compare two bit arrays to see if they are identical or not, so I came with a function that doesn't look too performant to me, seems like it could be better since there are three logical operations in a single line. I'm wonder if it's posible to simplify it.
Public Overloads Shared Function AreEqual(ByVal ba1 As BitArray, ByVal ba2 As BitArray) As Boolean
If ba1.Length <> ba2.Length Then
Return False
End If
Dim i As Integer
For i = 0 To ba1.Length - 1
If Not (Not ba1(i)) Xor ba2(i) Then
Return False
End If
Next
Return True
End Function
Edit:
After hours of testing and brainstorming, I came to my initial thoughts to reduce somehow the number of those three logical operators, and I put one of them into a variable, which means a single action to revert all bits at once instead of reverting bit by bit. This is the result, and is way much faster than previous one, about 3 times faster:
Public Overloads Shared Function AreEqual(ByVal ba1 As BitArray, ByVal ba2 As BitArray) As Boolean
If ba1.Count <> ba2.Count Then
Return False
End If
Dim revBa1 As BitArray = ba1.Not ' <<
Dim i As Integer
For i = 0 To ba1.Count - 1
If (Not revBa1(i)) Xor ba2(i) Then ' eliminates one logical operation existing here before
Return False
End If
Next
Return True
End Function
Now, faster than this one? :) Who knows, maybe...
Edit 2:
After some more testing and unconclusive results I noticed that the second version of the function is incorrect. Although it gets the right result, but it changes the ba1 value like it were passed byRef to the function:
'------------------------
'ba1 before = 000000000000000000000000000000001
'ba2 before = 000000000000000000000000000000001
'ba1 after = 111111111111111111111111111111110
'ba2 after = 000000000000000000000000000000001
'function result = True
'------------------------
Any ideas?
Edit 3:
The solution was simple, but the function isn't fast anymore:
Dim revBa1 As New BitArray(ba1)
revBa1 = revBa1.Not()
Edit 4:
Yes, this is it:
Public Overloads Shared Function AreEqual(ByVal ba1 As BitArray, ByVal ba2 As BitArray) As Boolean
If ba1 Is Nothing OrElse ba2 Is Nothing Then
Return False
End If
If ba1.Count <> ba2.Count Then
Return False
End If
Dim i As Integer
For i = 0 To ba1.Count - 1
If ba1(i) Xor ba2(i) Then
Return False
End If
Next
Return True
End Function
I guess sometimes we don't see the forest because of trees :)
ba1(i) and ba2(i) return Booleans that can be compared directly:
Function AreEqual(ba1 As BitArray, ba2 As BitArray) As Boolean
If ba1.Count <> ba2.Count Then Return False
For i = 0 To ba1.Count - 1
If ba1(i) <> ba2(i) Then Return False
Next
Return True
End Function
BitArray uses Integer array to store the bits, so for bigger BitArray (maybe about 100 bits? you might have to test that) it might be a bit faster to copy them to integer array before comparing:
Function AreEqual(ba1 As BitArray, ba2 As BitArray) As Boolean
If ba1.Count <> ba2.Count Then Return False
If ba1.Count < 64 Then ' needs some testing to determine this number
For i = 0 To ba1.Count - 1
If ba1(i) <> ba2(i) Then Return False
Next
Else
Dim a1 = New Integer((ba1.Length - 1) \ 32) {}
Dim a2 = New Integer((ba2.Length - 1) \ 32) {}
ba1.CopyTo(a1, 0)
ba2.CopyTo(a2, 0)
For i = 0 To a1.Length - 1
If a1(i) <> a2(i) Then Return False
Next
End If
Return True
End Function
As a side note, shorter and slower way to compare enumerable collections is SequenceEquals:
Function AreEqual(ba1 As BitArray, ba2 As BitArray) As Boolean
Return ba1.Cast(Of Boolean).SequenceEqual(ba2.Cast(Of Boolean))
End Function

Visual Basic - function to check if number is binary or not

Im code newbie and im stuck with this code. It appears that i always get True as response from this function. What am i doing wrong ?
Private Function binary() As Boolean
Dim number, temp As Integer
Dim status As Boolean
TextBox1.Text = number
status = True
While (True)
If (number = 0) Then
Exit While
Else
temp = number Mod 10
If (temp > 1) Then
status = False
Exit While
End If
number = number / 10
End If
End While
Return status
End Function
You have your assignment the wrong way around:
TextBox1.Text = number
With this, number will always be 0, its initial value, so your While loop exits immediately, every time. It should be:
number = Convert.ToInt32(TextBox1.Text)
Or better yet, pass it in as a parameter to the function:
Private Function binary(number as Integer) As Boolean
Dim temp As Integer
Dim status As Boolean
status = True
While (True)
If (number = 0) Then
Exit While
Else
temp = number Mod 10
If (temp > 1) Then
status = False
Exit While
End If
number = number / 10
End If
End While
Return status
End Function
Then:
Dim isBinary as Boolean
isBinary = binary(Convert.ToInt32(TextBox1.Text))

Function 'DisplayArray' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used

I keep getting a error and because of this my code wont work. The error is "Function 'DisplayArray' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used". I can't get rid of this error. I'm new to programming, can anyone help?
Private Function DisplayArray() As String
Dim j As Integer = 0
ReDim Preserve Array(UpperSub)
Dim AddNum As Double = 0.0
txtAddNum.Focus()
If Double.TryParse(txtAddNum.Text, AddNum) Then
If AddNum > 100 Then
MessageBox.Show("Number must be below 100")
ElseIf AddNum < 0 Then
MessageBox.Show("Number must be above 0")
Else
Array(UpperSub) = CDec(AddNum)
UpperSub = UpperSub + 1
End If
Else
MessageBox.Show("Value has to be a number")
End If
txtAddNum.Clear()
txtDisplay.Clear()
For j = 0 To UpperSub - 1
txtDisplay.Text = txtDisplay.Text _
& CStr(Array(j)) & ControlChars.NewLine
Next
txtNumberOfScores.Text = CStr(UpperSub)
End Function
A Function is designed to return a result, using the Return keyword. Your Function does not have a Return statement. Since none of the possible code paths (determined by branching on the If statements as well as the flow from beginning to end) return a value, you're getting this part of the error message: "Function 'DisplayArray' doesn't return a value on all code paths."
The second part of the error message means that if you tried to assign the return value of the Function to a variable, like this:
Dim result As String = DisplayArray()
You'd get a null value, as nothing is returned from the function.
The simplest solution is to change from a Function to a Sub. Subs in VB.NET do not return a value. So change
Private Function DisplayArray() As String
To
Private Sub DisplayArray()
And
End Function
To
End Sub
Note that the As String() in the Function declaration says this method will return a value that is a String, and the Sub has no return value (again, because it doesn't return a value).
To make this a Function that returns a value, you'll have to return at least one value from the method. Here's an example:
Private Function DisplayArray() As String
Dim j As Integer = 0
ReDim Preserve Array(UpperSub)
Dim AddNum As Double = 0.0
txtAddNum.Focus()
If Double.TryParse(txtAddNum.Text, AddNum) Then
If AddNum > 100 Then
MessageBox.Show("Number must be below 100")
Return String.Empty
ElseIf AddNum < 0 Then
MessageBox.Show("Number must be above 0")
Return String.Empty
Else
Array(UpperSub) = CDec(AddNum)
UpperSub = UpperSub + 1
txtAddNum.Clear()
txtDisplay.Clear()
For j = 0 To UpperSub - 1
txtDisplay.Text = txtDisplay.Text _
& CStr(Array(j)) & ControlChars.NewLine
Next
Return CStr(UpperSub)
End If
Else
MessageBox.Show("Value has to be a number")
Return String.Empty
End If
End Function
Essentially, if the validation fails, an empty string is returned. If the validation passes, the rest of the code is executed and the string value of UpperSub is returned.
You could then assign it to the TextBox like this:
txtNumberOfScores.Text = DisplayArray()
The above is a simple example based on your posted code, intended to show you how to return values from a Function. Adjust it to fit your needs (or use a Sub instead). Given that you want to update the display of the txtDisplay with the array and txtNumberOfScores as well you should do fine with a Sub.

Check String if it has an ascii like "/" and ":" using VBA

Here's my code but i want to know how will I know if the string has special characters like '/' or ':'.Many Thanks. Much great if you can edit my function.
Do Until EOF(1)
Line Input #1, LineFromFile <-----LineFromFile is the string
If HasCharacter(LineFromFile) = True Then
MsgBox "This File should be uploaded to FilePath2"
Else
Blah Blah Blah.......
This is my function
Function HasCharacter(strData As String) As Boolean
Dim iCounter As Integer
For iCounter = 1 To Len(strData)
If ....(Don't know what to say) Then
HasCharacter = True
Exit Function
End If
Next iCounter
End Function
Change your code to this:
Function HasCharacter(strData As String) As Boolean
If InStr(strData, "/") > 0 Or InStr(strData, ":") > 0 Then
HasCharacter = True
Else
HasCharacter = False
End If
End Function
The function InStr returns the position of the string if found, else it returns 0.
You can simply:
if strData like "*[:/]*" then
msgbox "This File should be uploaded to FilePath2"
else
...
Use InStr(stringToCheck, characterToFind)
Function HasCharacter(strData As String) As Boolean
If InStr(strData, "/") + InStr(strData, ":") > 0 Then
HasCharacter = True
End If
End Function
InStr returns 0 if the character cannot be found in the string. In this case, I add the positions of both special characters together. If the sum of these positions is greater than 0, we know that it contains at least one special character. You can separate this logic if you'd like.
if you have multiple characters then can also invert the checking and its easier to edit than multiple or statements
Function HasCharacter(strData As String) As Boolean
Dim iCounter As Integer
For iCounter = 1 To Len(strData)
If Instr ("/:", Mid (strData, iCounter, 1)) > 0 Then
HasCharacter = True
Exit Function
End If
Next iCounter
End Function

FILTER Function for integers - VBA

I searched the website but was not succesfful and tried doing some research on this but facing with " Type Mismatch" error.
I declared an array as integer type but the FILTER function seems to work only with STRING's. Can you please let me know how I can use the FILTER function for integers?
If UBound(Filter(CntArr(), count)) > 0 Then
msgbox "found"
End If
as i understand you need to know if specified count present in array. You can use for loop for it:
Dim found as Boolean
found = False
For i = 0 To UBound (CntArr())
If CntArr(i) = count Then
found = True
Exit For
End If
Next i
If found Then msgbox "found" End If
Below I have created IsIntegerInArray() function that returns boolean. Follow the two Subs for an example of integer array declaration. Declaring array as Integer should also prevent some unnecessary bugs caused by implicit data conversion.
Sub test_int_array()
Dim a() As Integer
ReDim a(3)
a(0) = 2
a(1) = 15
a(2) = 16
a(3) = 8
''' expected result: 1 row for each integer in the array
Call test_printing_array(a)
End Sub
Sub test_printing_array(arr() As Integer)
Dim i As Integer
For i = 1 To 20
If IsIntegerInArray(i, arr) Then
Debug.Print i & " is in array."
End If
Next i
End Sub
Function IsIntegerInArray(integerToBeFound As Integer, arr() As Integer) As Boolean
Dim i As Integer
''' incorrect approach:
''' IsIntegerInArray = (UBound(Filter(arr, integerToBeFound)) > -1) ' this approach searches for string, e.g. it matches "1" in "12"
''' correct approach:
IsIntegerInArray = False
For i = LBound(arr) To UBound(arr)
If arr(i) = integerToBeFound Then
IsIntegerInArray = True
Exit Function
End If
Next i
End Function