Home > DeveloperSection > Forums > Random Number Generator issue in C#
E E Cummings
E E Cummings

Total Post:26

Points:182
Posted on    October-14-2013 7:30 AM

 C# C# 
Ratings:


 1 Reply(s)
 708  View(s)
Rate this:

I want to add a random number to a list to be used as a ID number and then exports it to Excel. However i cam across a probelm when using more than 2 data members in my datafile: The Random numbers i generate double up, causing my program to crash.


static Dictionary<string,Backup> getData()

{

    Dictionary<string, Backup> bDict = new Dictionary<string, Backup>();

    StreamReader reader = new StreamReader("/data/storedata.txt");

    while (!reader.EndOfStream)

    {

        string line = reader.ReadLine();

        string[] parts = line.Split(' ');

        string item = parts[0];

        string owner = parts[1];

        Random rnd = new Random();

        int test = rnd.Next(item.Length+10000);//For every 'item' a Random number is generated.(the +10000 is simply to produce a 4-digit number)

        //Console.WriteLine(test);//Testing 

        Backup BP = new Backup(item, owner,test);

        bDict.Add(test.ToString(), BP);//Adding to the Dictionary.

        //Console.WriteLine(string.Format("{0}, {1}, {2}", item, test, owner));

    }

    return bDict;

}//Read file, Grabed data and stored it in a List.

 



Andrew Deniel
Andrew Deniel

Total Post:29

Points:203
Posted on    October-14-2013 7:51 AM

The Random numbers i generate double up, causing my program to crash.

You just have to check if the number already exists in the Dictionary:

while(bDict.ContainsKey(test.ToString()))

    test = rnd.Next(item.Length + 10000);


Modified On Oct-16-2013 10:19:40 AM

Don't want to miss updates? Please click the below button!

Follow MindStick