troubleshooting Question

simple C# method to generate string of random words returns unexpected results

Avatar of matticus
matticus asked on
C#
9 Comments1 Solution2844 ViewsLast Modified:
Hello,

I have a simple method that opens a text file with a list of 10,000 words and generates a random string from those words. Here is the method:

        private string GetWords()
        {
            string sentence = "";

                StreamReader r;

                for (int y = 0; y < 10; y++)
                {
                    r = File.OpenText("C:\\words.txt");

                    Random rand = new Random();
                    int next = rand.Next(1,10000);

                    for (int x = 0; x < next; x++)
                    {
                        r.ReadLine();
                    }

                    sentence += r.ReadLine() + " ";

                    // MessageBox.Show(sentence);
                }

                return sentence;
        }

For some reason, the strings this method returns look like this:

       CAR CAR CAR CAR CAR TIGER TIGER ROOSTER ROOSTER ROOSTER

If I insert the statement MessageBox.Show(sentence) after each iteration of the second loop, however, the string returne is exactly what I would expect; something like:

       CAR APPLE DOG ZEBRA LION BEAR TIGER EMU ROOSTER FOX

This may be an utterly simple oversight, but I have gone over and over the logic and cannot seem to figure out why I am getting unexpected return values like in the first example.

Any ideas would be greatly appreciated.

Thanks ahead of time,
Matt
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 9 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 9 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros