【问题标题】:Random word picker picks sequences of the same letters?随机单词选择器选择相同字母的序列?
【发布时间】:2019-03-18 06:47:23
【问题描述】:

我正在制作一个在控制台中运行的简单的刽子手游戏。我创建了一个从列表中选择随机单词的方法,以便稍后实现作为答案。我创建了这个方法来做到这一点:

public static string GetWord()
{
    Random random = new Random();
    string[] words = new string[5]{"a", "b", "c", "d", "e"};
    return words[random.Next(5)];
}

我通过使用 for 循环将该方法循环 100 次来测试该方法:

static void Man(string[] args)
{
    for(int i = 0; i <101; i++)
    {
        Console.WriteLine(GetWord());
    }
}

我希望得到一组随机的字母作为输出。但是,当我运行程序时,情况并非如此。相反,我得到类似于:

d d d d d d d d d d d d d
d d d C C C C e e e e 电子
e d d d d d 一种 一个
一种 一种 一种 一种 一种 一种 一种 b b b b b b b b b b
b c c c c e e e e e e e e d d d d a a a a a a a a a e e b b b b b b b b d d d d c c c c c c e

是不是我做错了什么?如果是这样,我该怎么做才能解决这个问题?提前谢谢你

【问题讨论】:

标签: c# random console-application generator


【解决方案1】:

试试这个:

private static readonly Random Random = new Random();

public static string RandomString(int length)
{
    const string chars = "abcde";
    return new string(Enumerable.Repeat(chars, length).Select(s => s[Random.Next(s.Length)]).ToArray());
}

static void Man(string[] args)
{
   Console.WriteLine(RandomString(100));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2013-12-06
    相关资源
    最近更新 更多