I am new to programming in C# and I'm having problems generating random numbers from input read form a file. I am trying to generate random numbers from the second field on each line from the following input read from a text file
4321,99
5432,79
6543,59
7654,39
The file is read by the following code, then parsed into separate fields where a method is called to generate a random number
private void readFileButton_Click(object sender, EventArgs e)
{
string readString;
inputFile = File.OpenText(sourceFileString);
while (!inputFile.EndOfStream)
{
readString = inputFile.ReadLine();
var flds = readString.Split(',');
string patID = flds[0];
int months = Convert.ToInt32(flds[1]);
Random();
}
inputFile.Close();
}
The method I am using that generates a random number from the second field
private void Random()
{
Random rand2Integer = new Random();
randomInteger = rand2Integer.Next(1, months) + 1;
}
However, this exception is thrown: 'minValue' cannot be greater than maxValue, and I can't wrap my head around it. If I manually enter the data on a form using a text box then the random number is generated as expected. Any input to guide me along?
From your code it looks like you have a class variable months. However, while reading file you have declared a local variable which essentially hides the class variable.
Now when you use Random function, the class variable is used (which must have 0 and causing this error)
replace the following line of code
int months = Convert.ToInt32(flds[1]);
with
months = Convert.ToInt32(flds[1]);
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