Question about dictionaries

Why do I get an exception for this:

[code] Dim tmp_string() as String = Split(“F1,F2,F3,F4,F5,F6,F7,F8,F9,F10”, “,”)

dim mydict as Dictionary

dim zz as Integer
for zz=0 to ubound(tmp_string)
dim astring as string
astring = tmp_string(zz)
mydict.value(astring)=zz // Why an exception here???
Listbox1.AddRow(tmp_string(zz))
dim bstring as string
bstring = hex(mydict.Value(astring))
Listbox1.AddRow(bstring)
next[/code]

Try:

dim mydict as new Dictionary

Are these the results you are after?

What are you trying to accomplish? Converting F1, F2 etc. to Hex?

To clarify Mike’s answer (after he seems to have gone the extra mile — nice job!), you must create an instance of a class before you can use it. dim mydict as Dictionary just says, “mydict will hold a dictionary,” but it starts as nil. The shorthand dim mydict as new Dictionary is the same as:

dim mydict as Dictionary
mydict = new Dictionary

Glenn I figured you are trying to convert your Fx characters to Hex or Ascii. I wrote this to test your original post.

I wasn’t sure why you were looking for the dictionary so I removed it trying to guess :slight_smile:

Note: This breaks when you go past F9 as I didn’t break the characters down into a Memory Block to convert them to ascii/hex (properly) :). Was this the path you were looking at?

HTH.

  Dim tmp_string() as String = Split("F1,F2,F3,F4,F5,F6,F7,F8,F9", ",")
  Dim String1, String2, String1ToASC, String2ToASC as String
  for zz as Integer =0 to ubound(tmp_string)
    String1 = tmp_string(zz).mid(1,1)
    String2 = tmp_string(zz).Mid(2,1)
    String1ToASC = Str(Asc(String1))
    String2ToASC = Str(Asc(String2))
    Listbox1.AddRow(tmp_string(zz)+ "      ASCII ("+String1ToASC + ","+ String2ToASC+")"+ "    HEX ("+hex(String1ToASC) + ","+ hex(String2ToASC)+")")
  next zz

My example was bizzar I will admit.

I want to create a lookup table that goes both way. The array of strings allows me to put in an integer and back a string. Then the dictionary was to allow me to put in a string and get back a number

Can you give an example of each direction? Are you looking for a String to convert to a Ascii or hex value? A correlation example would help. Thanks!

Array.indexof will give you the integer value of the position of the string.

Dim i As Integer = tmp_string.IndexOf(“F10”)

should give 9 as the result.

Please note I’m doing this off-line, so some adjustments may be necessary.

Awesome Wayne :slight_smile: Since you are offline here is a link to then Xojo Docs for Indexof. It has a great example relevant to Glenn’s post.

Xojo IndexOf Doc

You might check out my “two-way dictionary” article in xDev 9.5 (Article 9509: : A Two-Way Dictionary) – the download is free though you have to buy the issue to read the article.

The advantage of a dictionary versus an array is speed, which is only important if you have a large dataset you want to do this with.

The indexof was exactly what I was looking for. Thank you