I am reading an sms from a phone. I am trying to store the sms message - it is supposed to be stored in PDU_count(PDU) where PDU = 3. It works no problem, however sometimes it says that the index is outside of the array. If i stop and restart, then run again (i.e reading same text again) it works.Is there a way to check whether the position exists or something and if it doesnt run the code again or something?
That is where the problem lies, but I think there is an underlying problem with the design. You expect that there will always be at least three items in the message once it has been split. If you are ever wrong about that then your code will fail on one of the earlier lines. In other words, your message must have at least two vbCRLF characters in it for the code to work. In lots of messaging systems, partial or junk messages might arise, either of which is probably not going to have the number of elements you expect. Therefore, you should always be checking the count before you assume that you have items 1 or 2 (it's pretty safe to say that you have item 0). A problem of this type could explain why the message sometimes fails, then works the next time.
The next issue is element PDU. You do need to check the count on that one, unless it is 0. However, it is also likely that PDU is being set wrong. Since we can't see where PDU is set, that's all that can be said, but you seem to expect that the array will have element PDU. Perhaps the fact that it does not is simply a symptom of a bug setting PDU.
Cheers guys. I changed my technique to use UBound, however I have just noticed what is stored in the array (attached). Is there a way therefore I can get it to find the "longest" array position or something? I am struggling to find something that occurs everytime to stop this happening once in a blue moon.
Dim words As String() = _
{ _
"First element", _
"I am the longest element in this array", _
"Shorty" _
}
Dim Result = _
( _
From x In words Where x.Length = _
(Aggregate word In words Into Max(word.Length)) Select x _
).FirstOrDefault
If Result IsNot Nothing Then
MsgBox(Result)
End If
I'm not quite as sold on LINQ as others. You can write some sweet looking code, but for simple loops it is also slower code. That usually doesn't matter, but in cases where you are trying to save time, it can matter.
A loop that would find the longest items would look like this:
Code:
dim max as integer = 0
dim maxIndex as integer
For x As Integer = 0 to PDU_count.Count - 1
if PDU_Count(x).Length > max Then
max = PDU_Count.Length
maxIndex = x
End If
Next