开发者

Grabbing Random from ArrayList

I have an ArrayList which stores 52 card objects like so:

 public class Pack

{
   private ArrayList<Card> cards;
   private Card RandomCard;


   public static void main(String[] args) {
    ArrayList<Card> cards = new ArrayList<Card>();

    cards开发者_Go百科.add(new Card('C','A'));
    cards.add(new Card('C','2'));
    cards.add(new Card('C','3'));

etc..

I also have this method which generates a random number to grab a random object from my ArrayList.

public Card getRandomCard()

{
   int number = (int) (Math.random() * 52.0);
   return RandomCard;
}

This compiles but when I test it I get returned 'null'. I have to include this method! Any suggestions?


try

return cards.get(number);

instead of

return RandomCard;

The last statement returns RandomCard var, which isn't assigned anywhere.


Try this:

public Card getRandomCard() {
    return cards.get((int) (Math.random() * cards.size()));
}

Alternative using Random:

public Card getRandomCard() {
    Random gen = new Random(); // Make this an instance variable instead.
    return cards.get(gen.nextInt(cards.size()));
}

Edit:

Your original code tries to initialize an ArrayList of Cards in the main method (line 9), which is a completely different ArrayList from your ArrayList in Pack. This means the ArrayList in Pack (line 4) remains null, which explains your NullPointerException described below. Replace your code with this:

public class Pack {

    private ArrayList<Card> cards;
    private Random random;

    public Pack() {
        random = new Random();
        cards = new ArrayList<Card>();

        cards.add(new Card('C','A'));
        cards.add(new Card('C','2'));
        cards.add(new Card('C','3'));
        // And so on..
    }

    public Card getRandomCard() {
        return cards.get(random.nextInt(cards.size()));
    }

    public static void main(String[] args) {
        Pack pack = new Pack();
        Card randomCard1 = pack.getRandomCard(); // Here is your random card.
        Card randomCard2 = pack.getRandomCard(); // Here is another random card.
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜