tags:

views:

60

answers:

3

I'm writing a script to take a string of letters and convert them to phonetic values. The problem I'm having is that I am unable to reference a value in a hashtable (see error below). I'm not sure why as the code looks fine to me.

Index operation failed; the array index evaluated to null.
At C:\Scripts\test.ps1:8 char:23
    + write-host $alphabet[ <<<< $char]
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArrayIndex

}

param($string = $(throw 'Enter a string'))

$alphabet = @{
"A" = "Alfa";
"B" = "Bravo ";
"C" = "Charlie ";
"D" = "Delta ";
"E" = "Echo ";
"F" = "Foxtrot ";
"G" = "Golf ";
"H" = "Hotel ";
"I" = "India ";
"J" = "Juliett";
"K" = "Kilo ";
"L" = "Lima ";
"M" = "Mike ";
"N" = "November ";
"O" = "Oscar ";
"P" = "Papa ";
"Q" = "Quebec ";
"R" = "Romeo ";
"S" = "Sierra ";
"T" = "Tango ";
"U" = "Uniform ";
"V" = "Victor ";
"W" = "Whiskey ";
"X" = "X-ray";
"Y" = "Yankee ";
"Z" = "Zulu ";
}

clear-host
$charArray = $string.ToCharArray()
foreach ($char in $charArray)
{
    write-host $alphabet[$char]
}
A: 

Methinks you need to lose the space after each letter in your array. And you are also missing a space after Alfa, Juliett (sp), and X-ray.

$alphabet = @{
"A"  =  "Alfa ";
"B"  =  "Bravo ";
"C"  =  "Charlie ";
"D"  =  "Delta ";
"E"  =  "Echo ";
"F"  =  "Foxtrot ";
"G"  =  "Golf ";
"H"  =  "Hotel ";
"I"  =  "India ";
"J"  =  "Juliet ";
"K"  =  "Kilo ";
"L"  =  "Lima ";
"M"  =  "Mike ";
"N"  =  "November ";
"O"  =  "Oscar ";
"P"  =  "Papa ";
"Q"  =  "Quebec ";
"R"  =  "Romeo ";
"S"  =  "Sierra ";
"T"  =  "Tango ";
"U"  =  "Uniform ";
"V"  =  "Victor ";
"W"  =  "Whiskey ";
"X"  =  "X-ray ";
"Y"  =  "Yankee ";
"Z"  =  "Zulu ";
}
John Kugelman
Thanks for pointing that out. But that was a error with the i formatted the post. The original code doesn't have any spaces.
SuperFurryToad
A: 

Your problem is that in $alphabet[$char], $char is null. Where does $chararray come from?

Gabe
Sorry, the line where I created the char array was missing when I pasted in the code. I've added it back in now
SuperFurryToad
That's not going to work; `$alphabet`'s keys are strings, while `$char` is a char. You want `$alphabet[$char.ToString()]`, but it still doesn't explain where the null comes from.
Gabe
$alphabet[$char.ToString()] did the trick. Now it's working, thanks.
SuperFurryToad
A: 

Each Char is a rich object, Change:

write-host $alphabet[$char]

to

write-host $alphabet["$char"]

or

write-host $alphabet[$char.ToString()]

Shay Levy