dimanche 11 novembre 2018

How to generate a random index into my ArrayList?

So I have a class Cup which is part of a game for class. The public int select() method has to return a move in c. I need to generate a random index into c, and I'm told to do this by generating a random number from zero up to and not including the size of the ArrayList. Here's what I have:

import java.util.ArrayList;
import java.util.Random;
public class Cup {

ArrayList<Integer> c = new ArrayList<Integer>();
private Random r;

public Cup()
{
c.add(1);
c.add(2);
c.add(3);
Random r = new Random();
}
public int count()
{
return c.size();
}

public int select()
{
int index = r.nextInt(c.size());
return c.get(index);
}

public void remove(int m)
{
c.remove(m);
}
}

When I compile this in the game I'm using, it compiles correctly but tells me there's a Null Pointer exception on the line where r.nextInt(c.size()) is. Just very confusing because I feel like this should be right. Thank you!!!




Aucun commentaire:

Enregistrer un commentaire