Click here to Skip to main content
15,895,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm new to coding and I'm having some troubles with this piece of code.
Players' name and score are the same for both players when I run the program but different when I debug. Why is that?

C#
private string name;
private int ID;
private static int nextID = 1;
private int score;

public void Test()
{
    Player player1 = new Player();
    player1.Register();
    player1.SetRandomInfo();
    Console.WriteLine(InfoToString(player1));

    Player player2 = new Player();
    player2.Register();
    player2.SetRandomInfo();
    Console.WriteLine(InfoToString(player2));
}

public void SetRandomInfo()
{
    Random randomGen = new Random();
    int random = randomGen.Next(100);
    name = "player" + random;
    random = randomGen.Next(20);
    score = random;
}
Posted
Comments
frostcox 22-Mar-13 11:53am    
Inside SetRandomInfo()
set score = 0 and name = "" at the start

You should not initialize your randomGen variable each time you call the SetRandomInfo() method.

Better create a class-wide Random variable, initialize it in the constructor of the class (with a seed or not), and use it in your method.

Name, ID and score variables should be local ones, on the contrary.
 
Share this answer
 
Comments
Maciej Los 22-Mar-13 12:14pm    
Good idea!
+5!
phil.o 22-Mar-13 12:16pm    
Thanks Maciej ;)
Hello,

Try providing the initial seed value to the Random Number Generator. e.g.
C#
DrandomGen = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);

Regards,
 
Share this answer
 
Comments
phil.o 22-Mar-13 12:14pm    
It could do the trick (as long as name, ID and score variables are made local, see my solution).
But there is a performance penalty to initialize a Random at each iteration.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900