2012-10-09 17 views
1

這只是我的一部分代碼,但它引起了我的問題。該代碼的預期目的是獲取用戶輸入並將其作爲數組的大小。然而,它給我的錯誤「索引是在數組的界限之外」,無論我輸入什麼值。索引超出了Visual Basic中數組的範圍

下面是代碼:

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 

回答

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

謝謝,這是有道理的,我已經習慣了把我的思緒一起在開始,所以移動數組從未出現在我身上。謝謝你的幫助。 – DumbQuesionGuy314

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 
' ... 

至於圈,我爲你試圖完成什麼完全糊塗了,但它肯定看起來像有一個更好的方式來做到這一點。如果你要解釋你對這個循環的意圖,我可能會提出一個更好的算法。

0

如果我正確地看到它,您正在使用索引給候選人一個大小。但是在它從控制檯獲取值之前使用它。所以它的大小爲0. 在readline之後移動Dim狀態。 此外,你shoild使用像integer.tryparse讀取控制檯。

另外,我不明白你做的同時, 一對i =索引會更清晰的目的...