Well after a long time, I managed to get the out comes from my program I asked about in my first question. It add a random number to a list to be used as a ID number and then exports it to Excel. However I came 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.
What i'm after/trying to do is have a sort of check, that if two numbers are the same a new number is generated as a replacement(or some other way of doing the same thing). I've tried if statements but VS keeps asking if i meant to compare to something else. I've looked at things here on Stackoverflow, but the answers don't fit what is happening with my code. Any Help be appreciated.
FAQ datafile will have upwards of 500 'items' no min/max
cheers
The Random numbers i generate double up, causing my program to crash.
You have to reuse the same random instance, so create it outside the loop, otherwise it's seeded with he same time causing the same numbers.
MSDN:
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated.
Apart from that you have to check if the number already exists in the Dictionary:
Random rnd = new Random();
while (!reader.EndOfStream)
// ...
while(bDict.ContainsKey(test.ToString()))
test = rnd.Next(item.Length + 10000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With