使用数组时vb.net中的System.IndexOutOfRangeException

时间:2012-07-21 00:06:43

标签: vb.net

好吧,我已经尝试完成一项挑战,要求我从0到1000获得5或3的所有倍数,然后得到它们的总和,我是vb.net的新手所以我认为这样会对我来说是一个很好的挑战>我确信我的基础知识是对的,但我不太清楚为什么我会收到此错误:/。

Module Module1

    Sub Main()
        Dim Counter As Integer = 1
        Dim Numbers() As Integer
        Dim NumbersCounter As Integer = 0
        Dim Total As Integer = 0

        While (Counter <= 1000)

            If (Counter Mod 3 = 0) Then
                Numbers(NumbersCounter) = Counter '<--- The error is located on Numbers.
                NumbersCounter = NumbersCounter + 1
                Counter = Counter + 1

            ElseIf (Counter Mod 5 = 0) Then
                Numbers(NumbersCounter) = Counter
                NumbersCounter = NumbersCounter + 1
                Counter = Counter + 1

            Else
                Counter = Counter + 1
            End If

        End While

        Counter = 0

        While (Counter <= Numbers.Length)
            If (Counter = 0) Then
                Total = Numbers(Counter)
                Counter = Counter + 1
            Else
                Total = Total * Numbers(Counter)
                Counter = Counter + 1
            End If

        End While

        PrintLine(Total)

    End Sub

End Module

任何帮助或提示将不胜感激!提前谢谢。

2 个答案:

答案 0 :(得分:1)

您需要为Numbers数组分配内存,因为最初知道大小,您可以在声明时分配:

Dim Numbers(1000)As Integer

答案 1 :(得分:1)

在查看代码时,egghead说明你没有初始化你的数组是正确的。但在这样做之后,我不得不在代码中更改其他一些内容以使其运行。

Module Module1

    Sub Main()
        Dim Counter As Integer = 1
        Dim Numbers(1000) As Integer          'Initialized the Array so it will be usable.
        Dim NumbersCounter As Integer = 0
        Dim Total As Integer = 0

        While (Counter <= 1000)

            If (Counter Mod 3 = 0) Then
                Numbers(NumbersCounter) = Counter 
                NumbersCounter = NumbersCounter + 1
                Counter = Counter + 1

            ElseIf (Counter Mod 5 = 0) Then
                Numbers(NumbersCounter) = Counter
                NumbersCounter = NumbersCounter + 1
                Counter = Counter + 1

            Else
                Counter = Counter + 1
            End If

        End While

        Counter = 0

        While (Counter <= Numbers.Length - 1)  ' Arrays are zero based so you need to subtract 1 from the length or else you will overflow the bounds
            If (Counter = 0) Then
                Total = Numbers(Counter)
                Counter = Counter + 1
            Else
                Total = Total + Numbers(Counter)  'You were multiplying here not adding creating a HUGE number
                Counter = Counter + 1
            End If

        End While

        Console.WriteLine(Total)  'Changed PrintLine which prints to a file to Console.WriteLine which writes to the screen
        Console.ReadLine          'Added a Console.ReadLine so the Window doesn't close until you hit a key so you can see your answer

    End Sub

End Module