简体   繁体   中英

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.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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM