gpt4 book ai didi

java - 添加到ArrayList时出现NullPointer

转载 作者:行者123 更新时间:2023-12-01 14:43:57 27 4
gpt4 key购买 nike

我意识到已经有一堆这样的问题,但到目前为止我看到的每个问题都是 ArrayList 未初始化。我认为我的已初始化,但在尝试添加到列表时我得到一个空指针。这是我的代码:

import java.util.ArrayList;
import java.util.Random;
import java.util.Collections;

public class Deck {
static final int DECKSIZE = 48;
static final int MAX = 10;
static final int MIN = 1;
public ArrayList<Card> cardDeck = new ArrayList<Card>();
Random rand;

public Deck() {
initializeDeck();
}

private void initializeDeck() {
for (int i=0; i<DECKSIZE; i++) {
cardDeck.add(i, new Card("Name" + (i+1), "Race" + (i+1), "Orientation" + (i+1)));
}
}

public void shuffleCards() {
Collections.shuffle(cardDeck);
}
}

这是堆栈跟踪告诉我initializeDeck是一个空指针

Caused by: java.lang.NullPointerException
at hr.krypto.cardwars.deck.Deck.initializeDeck(Deck.java:24)
at hr.krypto.cardwars.deck.Deck.<init>(Deck.java:15)
at hr.krypto.cardwars.deck.Dealer.<init>(Dealer.java:14)
at hr.krypto.cardwars.model.CardTable.<init>(CardTable.java:15)
at hr.krypto.cardwars.screen.GameScreen.show(GameScreen.java:31)
at com.badlogic.gdx.Game.setScreen(Game.java:62)
at hr.krypto.cardwars.CardWarsGame.create(CardWarsGame.java:19)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:127)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:110)

最佳答案

考虑到方法 ArrayList.add(index, Element) 仅抛出 IndexOutOfBoundsException,该错误必定出现在您的卡类的构造函数中。

猜测最快的方法是调试卡类构造函数。

关于java - 添加到ArrayList时出现NullPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15656901/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com