0

I wan´t to get a random instance of an ArrayList, but my code always returns the same value.

public static void randomEvent(){
            Random rnd = new Random();
            int which = rnd.Next(1,events.Count);
            Debug.WriteLine("Which event: " + which);
            Debug.WriteLine("Count Events: "+ events.Count);
            ((Event) events[which-1]).write();
        }

The size of events.Count is 2.

Hobbit9797
  • 73
  • 5

2 Answers2

3

If events.Count is 2, then you're calling rnd.Next(1,2).

The documentation says that the first parameter is inclusive and the second parameter is exclusive. And you're returning an int. You're asking for an int x where 1 <= x < 2. So the only thing it CAN return is 1.

You should really be calling rnd.Next(0,events.Count) and then you only need to do events[which], not events[which-1].

Tim
  • 14,999
  • 1
  • 45
  • 68
2

Move Random rnd = new Random(); outside of the randomEvent() method.

private static Random rnd = new Random();

public static void randomEvent(){
    int which = rnd.Next(1,events.Count);
    Debug.WriteLine("Which event: " + which);
    Debug.WriteLine("Count Events: "+ events.Count);
    ((Event) events[which-1]).write();
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • static keyword is causing issues – Gabbar Apr 23 '13 at 17:30
  • Note that `Random` instances aren't thread safe, so if the event could potentially be triggered from multiple threads you need a way of handling that. – Servy Apr 23 '13 at 17:32