Link to home
Start Free TrialLog in
Avatar of John Gates, CISSP, CDPSE
John Gates, CISSP, CDPSEFlag for United States of America

asked on

Array Problems

The problem I have is when the arrContents(2) does not exist I get an exception.

How can I poll how many elements an array has before acting on it?
arrContents2 = Split(arrContents(1), delimiter2)
 
                LastName = arrContents2(0)
                FirstName = arrContents2(1)
                MiddleName = arrContents(2)

Open in new window

SOLUTION
Avatar of ZachSmith
ZachSmith
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Patrick Matthews
UBound(arrContents) gives the top index number, and LBound the starting index number.

For a multi-dimensional array, use the optional second argument of UBound or LBound
to specify which dimension you're interested in.
Check the length of the array before attempting to reference an item in the array. so if length == 1 you know you will not be able to access the second item in the array

Andrew
dimante,

My suggestion was for VB6 and VBA.  I have no idea if it works the same way in VB.net.

Regards,

Patrick
Avatar of John Gates, CISSP, CDPSE

ASKER

Here is the issue.

I have a text file with this content:


098898,Last First Middle,
098899,Last First,


When I split the file the second time what I am asking is how to get the value of how many items are in the array

Obviously the second time only arrContents2(0), and arrContents(1) exist.  How do you poll for this?

-D-
the second part was supposed to be arrContents2(1)
Do you get an index out of range exception?  If not could you tell us the exact exception you receieve

Andrew
dimante said:
>>Obviously the second time only arrContents2(0), and arrContents(1) exist.  How do you poll for this?

ZachSmith and REA_ANDREW already showed you how for VB.net, and I already showed you how
for VBA and VB6.
arrContents2 = Split(arrContents(1), delimiter2)
If arrContents2.GetUpperBound(0) >= 2 Then
    LastName = arrContents2(0)
    FirstName = arrContents2(1)
    MiddleName = arrContents(2)
Else
    MessageBox.Show("Missing Data In Line: " & arrContents(1))
End If
Idle thank you for your post.  The problem is even with that an exception error is still occurring:


Error Encountered:mscorlib System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices)
   at System.Array.GetValue(Int32 index)
   at Microsoft.VisualBasic.CompilerServices.Symbols.Container.GetArrayValue(Object[] Indices)
   at Microsoft.VisualBasic.CompilerServices.NewLateBinding.InternalLateIndexGet(Object Instance, Object[] Arguments, String[] ArgumentNames, Boolean ReportErrors, ResolutionFailure& Failure)
   at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexGet(Object Instance, Object[] Arguments, String[] ArgumentNames)
   at IDSystemTextRead.IDSystem.IDSystem_Load(Object sender, EventArgs e) in C:\Users\jgates.LAKEPARK\Desktop\IDSystemTextRead\IDSystem.vb:line 600

So that code is not working either...

-D-
check first whether the contents is null or nothing

If Not String.IsNullOrEmpty(arrContents2(0)) Then  LastName = arrContents2(0)
If Not String.IsNullOrEmpty(arrContents2(1)) Then  FirstName = arrContents2(1)
If Not String.IsNullOrEmpty(arrContents2(2)) Then  MiddleName = arrContents2(2)

Try that

Show us more complete code please...
That is not working either 8(
Here is the snippet...  It seems my Replace functions are not working either...  But that is for another question.  Hope this helps :-)

-D-
Dim sr As New StreamReader(FullPath)
 
            Do
                strContents = sr.ReadLine()
 
                'strContents.Replace("-", "")
                'strContents.Replace("*", "")
 
                'MsgBox(strContents)
 
                arrContents = Split(strContents, delimiter)
 
                'MsgBox(arrContents(0))
 
                strID = arrContents(0).ToString()
 
                'Now we need to split the firstname, middlename, and lastname
                
 
                arrContents2 = Split(arrContents(1), delimiter2)
 
                LastName = arrContents2(0)
                FirstName = arrContents2(1)
 
                'Console.WriteLine(arrContents2(2).Length.ToString)
                'MsgBox(arrContents2
                'MsgBox(UBound(arrContents2))
 
                If arrContents2.Length = 2 Then
                Console.WriteLine(arrContents2.Length)
                If (arrContents2(2)) = "" Then
                Console.WriteLine(arrContents2(0) & " " & arrContents2(1))
                Else
                Console.WriteLine(arrContents2.Length)
                MiddleName = arrContents2(2)
                MiddleName.Replace("-", "")
                MiddleName.Replace("*", "")
                Console.WriteLine(arrContents2(0) & " " & arrContents2(1) & " " & arrContents2(2))
                End If
 
 
            Loop Until strContents Is Nothing
 
            sr.DiscardBufferedData()
            sr.Close()

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
A couple things going on here. You need an ElseIf in your code to prevent arrContents(2) from being read if length = 2. You also should refer to your string variables in the console.writeline rather than the array variable.

Personally, I prefer Select Case since it's easier to read.
Dim sr As New StreamReader(FullPath)
Dim strContents As String = sr.ReadLine() 
            Do Until strContents = String.Empty
                arrContents = Split(strContents, delimiter) 
                strID = arrContents(0).ToString()
 
                'Now we need to split the firstname, middlename, and lastname              
                arrContents2 = Split(arrContents(1), delimiter2)
 
Select Case arrContents2.Length
Case 2
                LastName = arrContents2(0)
                FirstName = arrContents2(1)
 
Console.WriteLine(FirstName & " " & LastName) 
Case 3
                LastName = arrContents2(0)
                FirstName = arrContents2(1)
MiddleName = arrContents(2)
 
Console.WriteLine(FirstName & " " & MiddleName & " " & LastName) 
Case Else
End Select
 
strContents = sr.ReadLine()
 
            Loop
 
            sr.DiscardBufferedData()
            sr.Close()

Open in new window

I treated arrays differently with VB6
I would create a type then use it for the arrary.

Type NameArray
    LastName     = Str * 35
    FirstName     = Str * 25
    MiddleName =  Str * 25
    etc...
End Type

Then Create the array of type NameArray and use redim preserve to append to bottom.
Then I could quickly sort and move data around.
You would basically treat it like a recordset.
If you are interested let me know and I'll post the source.

Thanks
Roger
I don't think that a solution to use if else is really the best or switches for that matter, what happens if the array down the line requires 50 entries in some cases, that means 50 case statements or 50 if else statements.

Try and create a rule where by your array will always have a set number of items, even if those items are empty, as then you can code for empty using a single function OR throw exceptions upon populating the array from the Reader.

I work in C#, but I believe that prevention in this case is far better than the cause, and will mean it is far easier or quicker to maintain.

Andrew
Roger: If you're going to the trouble of creating a data structure, List(Of Name) is far, far better than using an array. It's typesafe for one, and doesn't require Redim to add a new element. Simply use .Add.

Andrew: I agree with you -- a fixed number of fields is better. You assume, of course, that the poster has control over the input file format.

Jeff
I have not had time to try these yet..  sadly this information (File) comes from a Unisys mainframe and I have no control over the format so I have to make it work.  I will try the posted methods and see if the outcome is positive.

Thanks to all that have submitted!

-D-
Thanks to everyone.  That was not a fun one at all :-)