Random number generator problems.

I got a little program that generates a random line of text from a .txt file and all is working well, at least for the most part.

On occasion I get an error message popup saying "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: Index."

Here's my code:

Dim ioFile As New System.IO.StreamReader("C:\\testfile.txt")
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While ioFile.Peek <> -1
lines.Add(ioFile.ReadLine())
End While
line = rnd.Next(lines.Count + 1)
RichTextBox1.AppendText(lines(line).Trim())
ioFile.Close()
ioFile.Dispose()

The last bit is where the random number is generated, which I am guessing where the problem itself is, but am unsure as to how to fix it...Any ideas?

Replies To: Random number generator problems.

Re: Random number generator problems.

Posted 26 November 2009 - 08:36 PM

Remember that a list index starts at zero. If you have two items in the list, its highest index will be 1. So you can't use .Count + 1 because Count would be 2 and + 1 would make it 3. Meaning the random number generator could possibly generate an index "2" which of course you don't have. You only have 0 and 1 as valid indexes.

I think you want line = rnd.Next(lines.Count). So if you have two items your Count will be 2 and random generator will generate numbers less than 2 (remember that the number you specify is actually excluded as a possible value). So by specifying 2, you will generate numbers 0 and 1, the valid indexes.