“Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index”

For creating a list with 100 random number between 0 and 1 I wrote below code that I receive the error.

      public List<float> random()
        {
            List<float> storerandomvalues = new List<float>(100);
            Random randomvalues = new Random();
            float randomnum;
            for (int counter = 0; counter < 100; counter++)
            {
                randomnum = 0f;
                randomnum = randomvalues.Next(1);
                storerandomvalues[counter]= randomnum;           //the error
            }
            return storerandomvalues;
        }

Answers


Use List<T>.Add method instead, storerandomvalues is not an array.You can't add items with indexer to a generic list.You can use indexer only to change existing items.

storerandomvalues.Add(randomnum);

You're creating empty storerandomvalues (without any items). Parameter in the List<> constructor is the list capacity only.

The best solution in your case is to use array instead of List<> (because in your case the number of items in the collection is constant):

var storerandomvalues = new int[100];
Random randomvalues = new Random();
float randomnum;
for (int counter = 0; counter < storerandomvalues.Length; counter++)
{
    randomnum = 0f;
    randomnum = randomvalues.Next(1);
    storerandomvalues[counter] = randomnum;        
}
return storerandomvalues;

use

storerandomvalues.Add(randomnum);

not

storerandomvalues[counter]= randomnum;    

Need Your Help

Button not being created programatically in dojo

javascript button dojo

I am using dojo version 1.6.1 and am trying to create a button. However, when I create the button programatically it doesn't show up correctly. It gives me a bullet point then the label of the butt...

Parse emails from Address Book

ruby regex ruby-on-rails-3 rubygems

Our application has an invite page where a user can import their address book. We're using an external service to get at them, so it just puts the results into a textarea. We started out just split...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.