我有一个存储52个卡对象的ArrayList,如下所示:
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'));
等。
我也有这个方法生成一个随机数来从我的ArrayList中抓取一个随机对象。
public Card getRandomCard()
{
int number = (int) (Math.random() * 52.0);
return RandomCard;
}
这编译但是当我测试它时,我得到'null'。我必须包括这种方法! 有什么建议?
答案 0 :(得分:4)
尝试
return cards.get(number);
而不是
return RandomCard;
最后一个语句返回RandomCard var,它没有在任何地方分配。
答案 1 :(得分:4)
试试这个:
public Card getRandomCard() {
return cards.get((int) (Math.random() * cards.size()));
}
替代使用随机:
public Card getRandomCard() {
Random gen = new Random(); // Make this an instance variable instead.
return cards.get(gen.nextInt(cards.size()));
}
修改强>
您的原始代码尝试在main方法(第9行)中初始化CardsList of Cards,这是与PackList中的ArrayList完全不同的ArrayList。这意味着Pack中的ArrayList(第4行)保持为null,这解释了下面描述的NullPointerException。用以下代码替换您的代码:
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.
}
}