Saturday, March 10, 2018

c# - Random.Next not working?





I'm trying to make a random room selector and Random.Next seems to not be working, please help!



List rooms = new List();
rooms.Add(room1);
rooms.Add(room2);
int index = Random.Next(rooms.Count);

System.Console.WriteLine(rooms[index]);


The systems I am using (I think this may be the problem)



Using System
Using System.Collections.Generic
Using.Collections



Using.Collections is greyed out.


Answer



your issue is that you want to call the Next method directly on the Random class, unfortunately, there is no static Next method for the Random class.



int index = Random.Next(rooms.Count);


you'll need to make an instance of the Random generator, in order to invoke the Next method.



Example:




Random rand = new Random();
int index = rand.Next(rooms.Count);
System.Console.WriteLine(rooms[index]);


further reading:



How do I generate a random int number in C#?


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...