声明二维数组



我有几项大学作业遇到了麻烦。真的,我只是对数组的一件事感到困惑。我需要声明一个三列五行的数组。前两列是整数,第三列是字母等级。因此,我对声明数据类型感到非常困惑,因为它们是不同的。这是我第一次使用数组,请原谅我的无知。这是我的数组应该是什么样子的。

Column 1 {0,300,350,400,450}
Column 2 {299,349,399,449,500}
Column 3 {F,D,C,B,A}

(这是一个评分应用程序)

我可以自己解决剩下的问题,我只是对这个数组部分感到困惑。所以我的问题严格来说是关于如何声明这样一个数组。它说是使用二维数组,这只会让我更加困惑,因为有三列。非常感谢。

二维数组是正确的。第一个索引是列,第二个索引是行。

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+"

请注意,Redim Preserve只能更改数组中的最后一个索引,这就是为什么我们按(column, row)顺序存储,而不是按更传统的(row, column)顺序存储。

有几种方法可以解决这个问题。一种是将数组声明为Object类型,然后将整数或字符串分配给相应的元素。不过,有些人认为这在社会上是不可接受的,因为这可能会导致代码难以调试。

您也可以为二维数组使用String类型,并将整数保存在字符串变量中。由于数值比较和计算所需的转换,通常也不会这样做。

另一种方法是使用包含这三个值的结构或类,并生成一个数组。

例如,

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"

最新更新