' System.IndexOutOfRangeException'

时间:2017-04-29 09:56:52

标签: arrays vb.net

索引超出了数组的范围

每次我尝试记录数据时,例如2 Farms和1 Bull我都会收到此错误...我认为这可能与ReDim有关。

每当有更多的农场,那么就会有公牛我有这个错误......但是如果它有1个农场,它可以带多少公牛。

    Private Farm() As FarmInfo
    Private Farms, Bulls, Weekends As Integer

    Private Structure FarmInfo
        Public FarmName As String
        Public FarmSize As Double
        Public Bull() As BullInfo
        Public LowestIncomeB As Double
        Public FarmRating As Double
    End Structure

    Private Structure BullInfo
        Public Income() As Integer
        Public AverageIncome As Double
    End Structure

    Private Sub DisplayGrid(ByVal R As Integer, 'subroutine with parameters
     ByVal C As Integer,
     ByVal T As String)

        grdOutput.Row = R 'row setting
        grdOutput.Col = C 'col setting
        grdOutput.Text = T 'printing

    End Sub

    Private Sub frmInkunziBreeding_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        grdOutput.DebugState = False
    End Sub

    Private Sub btnInput_Click(sender As Object, e As EventArgs) Handles btnInput.Click
        Dim nLoop As Integer

        Farms = CInt(InputBox("Enter in how many farms there are"))
        Bulls = CInt(InputBox("Enter in how many Bulls there are in total"))
        Weekends = CInt(InputBox("Enter in how many Weekends the bulls have been rented for"))

        ReDim Farm(Farms)


        For nLoop = 1 To Farms
            ReDim Farm(nLoop).Bull(Bulls)
        Next

        For nLoop = 1 To Farms
            ReDim Farm(nLoop).Bull(nLoop).Income(Weekends)
        Next

        Labels()

    End Sub

    Private Sub Labels()
        Dim nLoop As Integer

        grdOutput.Rows = Weekends + 6
        grdOutput.Cols = Farms + 1

        For nLoop = 1 To Farms
            DisplayGrid(0, nLoop, "Farm" & CStr(nLoop))
        Next

        DisplayGrid(1, 0, "Farm Name:")
        DisplayGrid(2, 0, "Farm Size:")

        For nLoop = 1 To Weekends
            DisplayGrid(nLoop + 2, 0, "Weekend " & CStr(nLoop) & ":")
        Next

        DisplayGrid(nLoop + 2, 0, "AverageIncome:")
        DisplayGrid(nLoop + 3, 0, "Lowest Income Bull:")
        DisplayGrid(nLoop + 4, 0, "Farm Rating:")


    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

您的ReDim语句的结构应为:

    Dim nLoopBulls As Integer

    ReDim Farm(Farms)

    For nLoop = 1 To Farms
        ReDim Farm(nLoop).Bull(Bulls)
        For nLoopBulls = 1 To Bulls
            ReDim Farm(nLoop).Bull(nLoopBulls).Income(Weekends)
        Next
    Next