外嵌套循环返回值两次?

时间:2014-04-22 19:36:36

标签: vb.net

我正在编写一个基本上通过二维数组运行的应用程序,并将数组中每个项的值乘以2,由于某种原因,外部循环每次重复时都会执行两次。为什么会这样?

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
    ' multiplies each array element by 2 and then displays the results in a list box

    Dim intInventory(,) As Integer = {{45, 67}, {2, 4}, {50, 7}, {9, 8}}

    For indexOuter As Integer = 0 To intInventory.GetUpperBound(0)
        intInventory(indexOuter, 0) *= 2
        lstInventory.Items.Add(intInventory(indexOuter, 0))

        For indexInner As Integer = 0 To intInventory.GetUpperBound(1)
            intInventory(indexOuter, indexInner) *= 2
            lstInventory.Items.Add(intInventory(indexOuter, indexInner))
        Next
    Next

End Sub

1 个答案:

答案 0 :(得分:2)

不要这样做:

    intInventory(indexOuter, 0) *= 2
    lstInventory.Items.Add(intInventory(indexOuter, 0))

因为第一次迭代(indexInner=0)覆盖了它:

    For indexInner As Integer = 0 To intInventory.GetUpperBound(1)
        intInventory(indexOuter, indexInner) *= 2
        lstInventory.Items.Add(intInventory(indexOuter, indexInner))