1

I'm trying to make a basic program that will take a letter a user inputs and output it's Morse code equivalent. My problem is that the program can't seem to locate the key. Any fixes? Please remember I'm trying to keep it as simple as possible.

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("A", ".-");
values.Add("B", "-...");
values.Add("C", "-.-.");
// ...
values.Add("8", "---..");
values.Add("9", "----.");
values.Add("0", "-----");

Console.WriteLine("Pleae enter the value you wish to convert"); 
string translate = Console.ReadLine();
string translateupper = translate.ToUpper();
if (values.ContainsKey(translateupper) == true)
{
    string Converted = (values["translateupper"].ToString());
    Console.WriteLine(Converted);
}
1
  • Please read How to Ask and provide a minimal reproducible example, along with your research. Don't show, and especially don't research your interpretation of the error ("can't seem to locate the key"), but research the exact exception message. Then step through your code and inspect the relevant variables. Commented Mar 16, 2017 at 15:44

1 Answer 1

5

Remove quotes around variable name:

string Converted = (values[translateupper].ToString());

Notes:

  • Value of dictionary entry is string - you don't need to convert it to string.
  • To avoid searching entry in dictionary two times, you can use TryGetValue method
  • Use camelCase names for variables in C#
  • Use dictionary initializer to provide initial values to dictionary
  • Consider to use Dictionary<char,string> because your keys are actually characters

With notes in mind:

var values = new Dictionary<string, string> {
      ["A"] = ".-",
      ["B"] = "-...",
      ["C"] = "-.-.",
      // etc
};

string translate = Console.ReadLine();
string converted;
if (values.TryGetValue(translate.ToUpper(), out converted))
    Console.WriteLine(converted);
// you can add 'else' block to notify user that translation was not found

With C# 7.0 you can declare out variable in place.

Sign up to request clarification or add additional context in comments.

1 Comment

And use static dictionary

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.