1

これは私のコードの一部にすぎませんが、問題が発生しています。コードの意図された目的は、ユーザーの入力を受け取り、それを配列のサイズにすることです。ただし、入力した値に関係なく、「インデックスは配列の範囲外でした」というエラーが発生します。

コードは次のとおりです。

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
4

3 に答える 3

1

まだ0に等しい場合は、配列のサイズを宣言しています。配列宣言を、入力された値に設定されてindexいる行の下に移動する必要があります。index

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

ループに関しては、あなたが何を達成しようとしているのか完全に混乱していますが、それを行うためのより良い方法があるように見えます。そのループの意図を説明する場合は、おそらくより良いアルゴリズムを提案できます。

于 2012-10-09T13:22:23.777 に答える
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
于 2012-10-09T13:22:41.687 に答える
0

正しく表示されている場合は、インデックスを使用して候補者にサイズを指定しています。ただし、コンソールから値を取得する前に使用します。したがって、サイズは0です。readlineの後にDim状態を移動します。また、integer.tryparseのようなものを使用してコンソールを読み取る必要があります。

さらに、私はあなたのdoの目的を理解していませんが、a for i =toindexはより明確になります...

于 2012-10-09T13:24:31.833 に答える