-7

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.

Community
  • 1
  • 1
Ryan
  • 3
  • 2
  • 3
    Ask yourself: how many times do I observe the variable changing? Now, in how many places do I change the variable? Do you see a connection between those two things? – Eric Lippert Mar 30 '16 at 02:25
  • 7
    Also, here is some good advice for new programmers. Believe me, you do not want to be asking StackOverflow every time you have a bug in your program. Learn your craft! http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Eric Lippert Mar 30 '16 at 02:27
  • you are calling random.Next only once in your constructor, hence nothing changes. – mentat Mar 30 '16 at 02:28
  • Thank you both, this clarifies my issue. Eric, I greatly appreciate you sharing that article. I'll be sure to give it a read to help prevent asking simple questions like this when avoidable. – Ryan Mar 30 '16 at 02:47

2 Answers2

2

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

Rob
  • 26,989
  • 16
  • 82
  • 98
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • Thank you, this answers my question. I was not thinking logically when i placed my this.Atk = random.Next(11); Line – Ryan Mar 30 '16 at 02:49
0

if you want to continue with a random number until it generate a breaking condition or number, you can modify the h() func as:

public int Atk;
public static int max = 100;

public void h()
{
    while (Atk != 10)
    {
        this. Atk = random.Next(max);
        Console.WriteLine(Atk);
    }
}
Rob
  • 26,989
  • 16
  • 82
  • 98