1 Replies - 2172 Views - Last Post: 26 November 2009 - 08:36 PM Rate Topic: -----

#1 tkdmaster  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-November 09

Random number generator problems.

Post icon  Posted 26 November 2009 - 08:04 PM

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?

Is This A Good Question/Topic? 0
  • +

Replies To: Random number generator problems.

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4359
  • View blog
  • Posts: 12,176
  • Joined: 18-April 07

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.

:)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1