2

I am trying to code a random generator using a list in the code behind. I am able to get a fully working number generator using the code below but I now want the generator to run through a list of places and not numbers but I'm stuck with it as I am completely new to developing.

Code for random number generator

private void btnGenerate_Click(object sender, EventArgs e)
{
    Random Place = new Random();
    int Places = Place.Next();
    txtResult.Text = Places.ToString();
}

As I said I want my generator to use places to eat (for example) but I am stuck

private void btnGenerate_Click(object sender, EventArgs e)
{
    Eat = new List<string>();
    Eat.Add("Tesco");
    Eat.Add("KFC");
    Eat.Add("Subway");
    Eat.Add("Chippy");

    Random Place = new Random();
    int Places = Place.Next();
    txtResult.Text = Places.ToString();
}

I tired commenting out the int Places = Place.Next(); and changing txtResult.Text = Places.ToString(); to txtResult.Text = Eat.ToString(); but this causes the following error to display in the field on my application when I click the 'Generate' button

System.Collections.Generic.List`1[System.String]

1 Answer 1

5

Try this:

List<string> Eat = new List<string>();
Eat.Add("Tesco");
Eat.Add("KFC");
Eat.Add("Subway");
Eat.Add("Chippy");

Random Place = new Random();
int Places = Place.Next(0, Eat.Count);
txtResult.Text = Eat[Places];

The line int Places = Place.Next(0, Eat.Count); will generate a random number within the range 0 to Eat.Count - 1. This will produce a valid index within your list. Then Eat[Places]accesses the randoly chosen string.

Sign up to request clarification or add additional context in comments.

4 Comments

Please explain what your code does. "give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime".
@CodeCaster i thought it's fairly obvious
It may be to you, but not to the next reader. Adding an explanation to your code also helps others to analyze your train of thought in order to figure out potential issues with the code you post. "Try this code block" always is a bad answer in my opinion, so thanks for your edit.
@Mithrandir If it was obvious enough to the person asking the question, they probably wouldn't have asked the question in the first place. Sure, they might be able to dig through your posted code and figure it out, but that might be expecting a little much of someone new to programming.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.