0

I'm new at C# so be easy on me please

I have a method which creates an elf, with a random age, strength (1-5) and speed.

For my main, I want to create a List of random elves, but I can not manage to do it

Lets say my elf class is:

class Elf

{
    public int age;
    public int strength;
    public int speed;

    Random rnd = new Random();

    public void newElf()
    {
        this.age      = rnd.Next(20, 50);
        this.speed    = rnd.Next(10, 20);
        this.strength = rnd.Next(1, 5);
    }    
}

So, how can I manage to complete a List with, lets say, 5 different elves(in my code, I ask the user how many elves does he want to create)

List<Elf> e = new List<Elf>()

*Sorry for the bad English, it is not my first language

Thank you

  • 1
    What does "can not manage to do it" mean? If you have attempted this but had problems, you should show us your best attempt and explain what the errors or undesired behavior are. – skrrgwasme Sep 09 '14 at 23:50
  • 1
    For the sake of learning I'm not going to give you the code. Try creating your elves in a loop and adding them to the list. – BradleyDotNET Sep 09 '14 at 23:56
  • search for how to add items to list. or check what is available to you in your list object(e) like explore "e. " . – loop Sep 10 '14 at 00:01

1 Answers1

0

First I'd restructure newElf() as a constructor:

public Elf()
{
    this.age      = rnd.Next(20, 50);
    this.speed    = rnd.Next(10, 20);
    this.strength = rnd.Next(1, 5);
} 

and in Main:

static void Main(string[] args)
{
    // look in the first argument for a number of elves
    int nElves = 0;
    List<Elf> e = new List<Elf>();
    if (args.Length > 0 && Int32.TryParse(args[0], out nElves))
    {
        for (int i = 0; i < nElves; i++)
        {
            e.Add(new Elf());
        }
    }
    else
        Console.WriteLine("The first argument to this program must be the number of elves!");
}

With this, you can pass the number of elves as a command line argument. Or, if you're looking to get it from the user after the program starts, try this thread.

Community
  • 1
  • 1
Gutblender
  • 1,340
  • 1
  • 12
  • 25
  • 1
    While correct, it seems clear to me that the OP has no clue on how to use loops. Without more explanation, you are basically just giving him the proverbial "fish", and not really helping him at all. – BradleyDotNET Sep 10 '14 at 00:23
  • It just seemed to me he was new to C# alone. But after reconsidering I think you're right. Even so, when someone gives me a fish, I won't rest until I can catch another by myself. – Gutblender Sep 10 '14 at 03:07