2016-07-10 6 views
0

いいから、Arrayからの名前を使って動的変数をIntegerとして作成したいと思います。これは私がこれまで試したものです:配列から動的変数を作成する

Dim subjects as Array {"Math", "English", "German"} 'Three example names 
Dim subjectsInt as New Dictionary(Of Integer) 'Throws error: Not enough arguments 
Dim i as Integer 

For i = 0 to 2 
    subjectsInt(subjects(i)) = 0 ' Trying to create a variable with the name of entry number i of the Array & and the starting value 0 

    Do 
     Console.WriteLine(subjects(1) & ": ") 
     Dim input As String = Console.ReadLine() 
     subjectsInt = CInt(input) 
    Loop While subjectsInt = 0 Or subjectsInt > 100 
Next i 

私はこのような結果を望んで最後に:

Math = 10  'random values between 1 and 100 
English = 40 
German = 90 

私は私の質問は、事前に感謝十分に明確であると思います:)

答えて

1

十分な議論がないのは間違いありません。辞書、具体的にはDictionary(Of TKey, TValue)は、キーのタイプとそれが使用する値のタイプの引数をとります。あなたはそれはあなたが最初のタイプをしなければならないだろう、ルックアップのためのあなたの文字列を使用したいと

String

Dim subjectsInt As New Dictionary(Of String, Integer) 

これは、実行して値にアクセスするあなたができるようになります:

subjectsInt(<your string here>) 

'Example: 
subjectsInt("Math") 
subjectsInt(subjects(0)) 'The first string (which is "Math") from the 'subjects' array. 

最初にキーを追加する必要がありますが、一度追加する必要があります。

subjectsInt.Add("Math", <your initial value here>) 

'You may use strings any way you can access them, for example: 
subjectsInt.Add(subjects(0), <your initial value here>) 
subjectsInt.Add(subjects(i), <your initial value here>) 
'etc... 

次に、あなたはちょうどあなたが望んでいたとして取得する/それを設定することができるはずです。

subjectsInt(subjects(i)) = CInt(input) 
+0

を、これは完璧:) –

+0

@BennoGrimmで、ありがとう聞くために!異なる時刻に値を追加/設定する場合は、[** 'Dictionary.ContainsKey()' **](https://msdn.microsoft.com/en-us/library/kw5aaea4(v = vs .110).aspx)メソッドを使用して、キーがすでに存在するかどうかを確認します。したがって、新しいエントリを追加するか、既存のエントリを変更する必要があるかどうかを知ることができます。 –

0

あなたはこのような何かを試みることができる:うれしい:

Sub Main() 

    Dim dic As New Dictionary(Of String, Integer) From {{"Math", 10}, {"English", 40}, {"German", 90}} 

    For Each entry In dic.Keys 
     Console.WriteLine(String.Format("{0}: {1}", entry, dic(entry))) 
    Next 

    Console.ReadKey() 

End Sub 
+0

あなたの助けをありがとうが、これは私が探していたものではありません:) –

関連する問題