-1

I'm am making a simple hangman game that runs in the console. I created a method that selects random words from a list to be later implemented as the answer. I created this method to do it:

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

And I tested the method by looping the method 100 times with a for loop:

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

I expect to get a random set of letters as output. However, when I run the program, this is not the case. Instead, I get something akin to:

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
e d d d d d a a
a a a a a a a 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 e b b b b b b b b d d d d d c c c c c c e

Is it something I'm doing wrong? If so, what can I do to fix this? Thank you in advance

Anas Alweish
  • 2,818
  • 4
  • 30
  • 44
  • Welcome to StackOverflow. Your question does not quite meet the standards that StackOverflow expects. Your question in its current state will likely not get accepted. I would highly suggest that you edit your question following the guidelines of [this StackOverflow article](https://stackoverflow.com/help/how-to-ask) – Marcello B. Oct 13 '18 at 04:58
  • Possible duplicate of [Random number generator only generating one random number](https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – Ňɏssa Pøngjǣrdenlarp Oct 13 '18 at 05:22
  • try to write `Random random = new Random();` outside of function `GetWord` then you will get your desired output. – er-sho Oct 13 '18 at 06:11

1 Answers1

1

try this :

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

enter image description here

er-sho
  • 9,581
  • 2
  • 13
  • 26
Anas Alweish
  • 2,818
  • 4
  • 30
  • 44