✅ Index was outside of bounds of the array
I've written a Morse Code translator, and it pretty much works 100% besides the fact it throws an exception "Index was outside of bounds of the array " every time I try to convert from Morse Code to English. The code uses dictionarys and the TryGetValue method to do the conversion.
9 Replies
int index = 0;
for (int morseIndex = 0; morseIndex <= morseInput.Length; morseIndex++)
{
string[] letterTokens = morseInput.Split(null);
char englishOutput;
morseToEnglishDictionary.TryGetValue(letterTokens[index], out englishOutput);
morseOutputTextBox.AppendText(englishOutput.ToString());
index++;
}
Probably should be
morseIndex < morseInput.Length
in the for
condition. If you have 5 objects your loop will run 6 times for index = 0,1,2,3,4,5. If you change it to <
instead of <=
then it will only run 5 times.
However the way the index
variable is redundant because thats what the morseIndex
is doing.
Also there are operations that you're performing in the loop that only need to be executed once such as morseInput.Split
and declaring the char
variable.
You can look to move them outside the loop to improve the efficiencyThanks, I'll try that. I only added the index outside to try the loop to just try something to get rid of the exception lol
I changed it to a while loop and I keep getting the index out of bounds exception
char englishOutput;
string[] letterTokens = morseInput.Split(null);
int morseIndex = 0;
while (morseIndex < morseInput.Length)
{
morseToEnglishDictionary.TryGetValue(letterTokens[morseIndex], out englishOutput);
morseOutputTextBox.AppendText(englishOutput.ToString());
morseIndex++;
}
Can you share the sample input that you're using?
- . ... - is what i'm trying to convert to english, it should be "test"
Oh I've figured it out
morseInput.Length is the number of characters in the string
but you're splitting based on tokens and iterating over the tokens
so you should use letterTokens.Length to limit your loop
I still think a for loop is preferred here
even better is probably a foreach loop
but hopefully you understand the problem you were having before?
thank you so much!!! my gut feeling knew it was something with the .length i was using
yes, it was because i was trying to use the length of the string which is very different than the length of the token
i owe you 1!!! 🙂
No stress, if theres no other questions, don't forget to $close
Use the
/close
command to mark a forum thread as answered