0

Ok, so i want to create dynamic Variables as Integer using the names from an Array. This is what I've tried so far:

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

in the end I want a result like this:

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

I hope my question is clear enough, thanks in advance :)

0

2 Answers 2

1

You're quite right that there's not enough arguments. A dictionary, more specifically a Dictionary(Of TKey, TValue), takes an argument for the type of key and the type of value it is going to use.

As you want it to use your strings for lookup you would have to make the first type a String:

Dim subjectsInt As New Dictionary(Of String, Integer)

This will make you able to access the values by doing:

subjectsInt(<your string here>)

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

Though you must be sure to add the key first, but you may only add it once:

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

Then you should just be able to get/set it as you wanted:

subjectsInt(subjects(i)) = CInt(input)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is just perfect :)
@BennoGrimm : Glad to hear! If you intend to add/set values at different times you can use the Dictionary.ContainsKey() method to check if a key already exists or not, thus you will know wether you have to add a new entry or just modify an already existing one.
0

You could try something like this:

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

1 Comment

Thanks for your help, but this isn't what i was looking for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.