Search code examples
c#randomconstructorclass-constructors

random number in constructor c#


I am a student taking an introductory programming course in line with game development. One of my assignments calls for me to define a players attack damage inside of the constructor. I want the damage to be random, but no matter what I do I get back the same number. This is a test I made to see how I can get this number to be random.

class MainChar
{
    public static Random random = new Random();
    public int Atk;        

    public MainChar()
    {
        this.Atk = random.Next(11);
    }

    public void h()
    {
        while (Atk != 10)
        {
            Console.WriteLine(Atk);

        }
    }
}

I'm creating a new instance of MainChar in my main program, and running h(). I get a repeating list of the same number instead of random numbers between 1 and 10. Any ideas?

P.S. This thread was useful, but could not answer my question.


Solution

  • In the method h(), the while forms an infinite loop if the atk!=10. so you need to specify an exit condition there to break the loop; you can use like this:

    public void h()
    {
        while (Atk != 10)
        {
            this.Atk = random.Next(11);                   
        }
        Console.WriteLine(Atk);
    }
    

    Now you will get a random number between 0 and 11 and is not 10 in the console