C# 如何在c中随机选择字符串
我正在写一个简单的语言翻译,它将呈现英文单词,并要求相应的外文单词。到目前为止,代码将从数组中选择一个随机词,但是我现在正试图让它从列表中选择相应的外来词。以下是迄今为止的代码:C# 如何在c中随机选择字符串,c#,arrays,string,visual-studio-2010,C#,Arrays,String,Visual Studio 2010,我正在写一个简单的语言翻译,它将呈现英文单词,并要求相应的外文单词。到目前为止,代码将从数组中选择一个随机词,但是我现在正试图让它从列表中选择相应的外来词。以下是迄今为止的代码: public class Words { public int spanishindex; string[] EnglishWords = { "Yellow", "Yello", "Yelow", "Yllow", "ellow" }; string[] Sp
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”
感谢您的帮助。问题是您调用了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;
}
}
问题是您调用了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;
}
}
更改:
string randomword = EnglishWords[randomizer.Next(index)];
到
。。。假设您不希望随机索引小于已随机找到的索引。更改:
string randomword = EnglishWords[randomizer.Next(index)];
到
。。。假设您不希望随机索引小于您已经随机找到的索引。您应该更改
string randomword = EnglishWords[randomizer.Next(index)];
到
你应该改变
string randomword = EnglishWords[randomizer.Next(index)];
到
作为旁注,随机随机化器=新随机;应该在函数之外,否则当您完成更多代码时,您将在几个小时内提出一个问题;应该在函数之外,否则当您完成更多代码时,您将在几个小时内提出问题。另一个需要注意的错误:在每次使用之前实例化Random可能会导致,尤其是在循环内调用GetRandomWord时-最好使用静态初始值设定项将randomizer设置为类字段。另一个需要注意的错误是:每次使用之前实例化Random可能会导致出现数字,特别是在循环内调用GetRandomWord时-最好使用静态初始值设定项将randomizer设置为类字段。