I have a couple of college assignments I am having trouble with. Really I am just confused about one thing regarding an array. I need to declare a three column, 5 row array. The first two columns are integers and the third column is the letter grade. So I am very confused about declaring the data type since they are different. This is my first go-around with arrays, so please excuse my ignorance. Here is an what my array is supposed to look like.
Column 1 {0,300,350,400,450}
Column 2 {299,349,399,449,500}
Column 3 {F,D,C,B,A}
(It's a grading app)
I can solve the rest of the problem myself, I am just confused about this array portion. So my question is strictly about how to declare such an array. It say's to use a two-dimensional array which only confuses me more since there are three columns. Thank you!
2-dimensional array is correct. First index is column, second index is row.
Dim strData(,) As String 'Use String variable type, even for the numbers
Dim intRowCount As Integer = 5
Dim intColumnCount As Integer = 3
ReDim strData(intColumnCount - 1, intRowCount - 1) 'subtract 1 because array indices are 0-based. Column 0 = Range start, Column 1 = Range End, Column 2 = Grade
'first row
strData(0, 0) = "0" 'Range start
strData(1, 0) = "299" 'Range end
strData(2, 0) = "F" 'Grade
'second row
strData(0, 1) = "300"
strData(1, 1) = "349"
strData(2, 1) = "D"
'third row
strData(0, 2) = "350"
strData(1, 2) = "399"
strData(2, 2) = "C"
'fourth row
strData(0, 3) = "400"
strData(1, 3) = "449"
strData(2, 3) = "B"
'fifth row
strData(0, 4) = "450"
strData(1, 4) = "500"
strData(2, 4) = "A"
'Add a row
intRowCount = intRowCount + 1
ReDim Preserve strData(intColumnCount - 1, intRowCount - 1)
'sixth row
strData(0, 5) = "501"
strData(1, 5) = "600"
strData(2, 5) = "A+"
Note that Redim Preserve
can only change the last index in the array, which is why we store in (column, row)
order rather than the more traditional (row, column)
order.
There are a couple of ways to approach this. One is to declare the array as Object type, and they assign integers or strings to the appropriate element. Some don't consider this socially acceptable, though, because it can lead to code that's difficult to debug.
You could also use a String type for a two dimensional array and save the integers in string variables. This is also not normally done because of the conversion necessary for numeric comparisons and computation.
Another approach is to use a structure or class that contains the three values, and make an array of that.
For example,
Structure Item
Dim col1 as integer
Dim col2 as integer
Dim col3 as string
End Structure
Dim itemList(20) as Item
itemList(4).col1 = 23
itemList(4).col2 = 45
itemList(4).col3 = "somestring"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With