0

我正在写一个简单的语言翻译器,它会呈现英文单词并询问相应的外来词。到目前为止,代码将从数组中选择一个随机词,但是我现在正试图让它从列表中选择相应的外来词。这是到目前为止的代码:

public class Words
    {
        public int spanishindex; 
        string[] EnglishWords = { "Yellow", "Yello", "Yelow", "Yllow", "ellow" };
        string[] SpanishWords= { "giallo", "giall", "iallo", "gllo", "lo" };

        public String GetRandomWord()
        {
            Random randomizer = new Random();
            index = randomizer.Next(EnglishWords.Length);
            string randomword = EnglishWords[randomizer.Next(index)];
            spanishindex= index;
            return randomword;
        }

        public String MatchSpanishWord()
        {
            string matchword = SpanishWords[spanishindex];
            return matchword;
        }
    }

我的想法是通过在 MatchSpanishWord 方法中传入与随机值相反的索引值,我会得到相应的单词(因为列表是按顺序排列的)

因此,如果选择了“ellow”,则对应的西班牙语应该是“lo”

任何帮助将不胜感激,谢谢。

4

3 回答 3

3

问题是您调用了 random 两次:一次生成随机索引,然后再次生成数组索引。我在下面的代码中修复了您的错误:

public class Words
{
    public int spanishindex; 
    string[] EnglishWords = { "Yellow", "Yello", "Yelow", "Yllow", "ellow" };
    string[] SpanishWords= { "giallo", "giall", "iallo", "gllo", "lo" };

    public String GetRandomWord()
    {
        Random randomizer = new Random();
        index = randomizer.Next(EnglishWords.Length);
        string randomword = EnglishWords[index]; //<---- this is the fix
        spanishindex= index;
        return randomword;
    }

    public String MatchSpanishWord()
    {
        string matchword = SpanishWords[spanishindex];
        return matchword;
    }
}
于 2013-03-20T19:51:24.740 回答
0

改变:

string randomword = EnglishWords[randomizer.Next(index)];

string randomword = EnglishWords[index];

...假设您不希望随机索引小于您已经随机找到的索引。

于 2013-03-20T19:51:33.013 回答
0

你应该改变

  string randomword = EnglishWords[randomizer.Next(index)];

  string randomword = EnglishWords[index];
于 2013-03-20T19:51:35.390 回答