索引是Visual Basic中数组的外部边界

时间:2012-10-09 13:18:01

标签: arrays vb.net visual-studio-2010

这只是我的代码的一部分,但它引起了我的问题。代码的预期目的是获取用户输入并使其成为数组的大小。然而,它给了我错误'索引超出数组的范围',无论我输入什么值。

以下是代码:

Option Explicit On
Option Strict On

Imports System

Module numbers
    Sub Main()
        'index decides number of candidates.
        Dim index as integer
        Dim candidate(index) as integer

        Console.Write("Please enter the number of candidates in the election: ")
        index=Convert.toInt32(Console.Readline())

        Do Until candidate(index) >= 0
            Console.Write(" Enter the name of candidate: ")
            candidate(index)=Convert.toInt32(Console.Readline())

            candidate(index) -=1
        Loop
    End Sub
End Module

3 个答案:

答案 0 :(得分:1)

index仍然等于0时,您正在声明数组的大小。您需要将数组声明移动到index设置为输入值的行下方:

' ...
Console.Write("Please enter the number of candidates in the election: ")
index=Convert.toInt32(Console.Readline())
Dim candidate(index) as integer
' ...

就循环而言,我对你想要完成的事情感到困惑,但看起来确实有更好的方法。如果你要解释你对这个循环的意图,我可能会建议一个更好的算法。

答案 1 :(得分:1)

你在这里遇到了一些问题。

首先,你需要初始化你的数组 你知道它有多大。

其次,你会发现For循环比Do循环更容易实现逻辑,因为你不需要手动跟踪循环计数器。

最后,您要将候选名称转换为整数。大多数人的名字都不是数字!

Sub Main()
    'index decides number of candidates.
    Dim index as integer

    Console.Write("Please enter the number of candidates in the election: ")
    index=Convert.toInt32(Console.Readline())

    ' We now know how big the array needs to be so you can initialise it.
    Dim candidate(index) as integer

    ' We use a For loop so that we don't have to worry about the 
    ' loop counter ourselves.
    For i As Integer = 0 to (index - 1)
        Console.Write(" Enter the name of candidate: ")
        ' Your candidate names appear to be an integer - 
        ' Surely that's not right??! I think you meant
        ' candidate(i) = Console.Readline()
        candidate(i)=Convert.toInt32(Console.Readline())
    Next
End Sub

答案 2 :(得分:0)

如果我看得正确,您使用的是索引给候选人一个大小。但是在从控制台获取值之前使用它。所以它的大小为0。 在readline之后移动Dim状态。 此外,您还可以使用integer.tryparse之类的东西来读取控制台。

另外,我不明白你做的目的, a for i = to index会更清楚...