2017-03-16 105 views
1

我正在嘗試製作一個基本程序,它將接收用戶輸入的一個字母並輸出它的摩爾斯等效代碼。我的問題是,程序似乎無法找到密鑰。任何修復?請記住我正試圖儘可能簡單。c#從字典中獲取值

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); 
} 
+0

請閱讀[問]並提供[mcve],以及您的研究。不要顯示,特別是不要研究你對錯誤的解釋(「似乎無法找到密鑰」),而是研究確切的異常消息。然後遍歷代碼並檢查相關變量。 – CodeCaster

回答

5

刪除周圍的變量名引號:

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

注:

  • 字典項的值是字符串 - 你不需要將其轉換爲字符串。
  • 爲了避免字典搜索條目兩次,你可以使用TryGetValue方法
  • 使用駝峯名變量在C#
  • 使用字典初始化器提供初始值字典
  • 考慮使用Dictionary<char,string>因爲你按鍵實際字符

與筆記記:

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 

使用C#7.0,您可以聲明變量。

+1

並使用靜態字典 –