首页 > 解决方案 > 检查单词是否正确后出现字典错误

问题描述

我用一些单词创建字典,从英语翻译成波兰语,从波兰语翻译成英语。从英语到波兰语的作品,它看起来像这样:

Dictionary<string, string> myDict =
new Dictionary<string, string>();

myDict.Add("Pies", "Dog");
myDict.Add("Kot", "Cat");
myDict.Add("Swinia", "Pig");
myDict.Add("Chomik", "Hamster");
myDict.Add("Ptak", "Bird");
myDict.Add("Mysz", "Mouse");
myDict.Add("Pszczola", "Bee");
myDict.Add("Niedzwiedz", "Bear");
myDict.Add("Krowa", "Cow");
myDict.Add("Kurczak", "Chicken");
myDict.Add("Kaczka", "Duck");
myDict.Add("Slon", "Elephant");
myDict.Add("Ryba", "Fish");
myDict.Add("Zaba", "Frog");
myDict.Add("Lew", "Lion");

if (textBox2.Text == myDict[textBox1.Text])
{
    MessageBox.Show("Dobrze");
    var rnd = new Random();
    int randomValue = rnd.Next(1, 15);
    string a = myDict.Values.ElementAt(randomValue);
    textBox2.Text = a;
}

但是从波兰语到英语不起作用,看起来像这样。

键入一个单词并检查后,弹出错误:

System.Collections.Generic.KeyNotFoundException:“给定的密钥不在字典中。”

Dictionary<string, string> myDict =
new Dictionary<string, string>();

myDict.Add("Pies", "Dog");
myDict.Add("Kot", "Cat");
myDict.Add("Swinia", "Pig");
myDict.Add("Chomik", "Hamster");
myDict.Add("Ptak", "Bird");
myDict.Add("Mysz", "Mouse");
myDict.Add("Pszczola", "Bee");
myDict.Add("Niedzwiedz", "Bear");
myDict.Add("Krowa", "Cow");
myDict.Add("Kurczak", "Chicken");
myDict.Add("Kaczka", "Duck");
myDict.Add("Slon", "Elephant");
myDict.Add("Ryba", "Fish");
myDict.Add("Zaba", "Frog");
myDict.Add("Lew", "Lion");

if (textBox2.Text == myDict[textBox1.Text])
{
    MessageBox.Show("Dobrze");
    var rnd = new Random();
    int randomValue = rnd.Next(1, 15);
    string b = myDict.Keys.ElementAt(randomValue);
    textBox2.Text = b;
}

我只改变

string a = myDict.Values.ElementAt(randomValue);

string b = myDict.Keys.ElementAt(randomValue);

标签: c#

解决方案


推荐阅读