gpt4 book ai didi

java - 尝试使用字段数组作为参数时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 03:10:56 25 4
gpt4 key购买 nike

所以我试图测试我的 DeckOfCards 数组是否能够正确打印。这是代码

public class Deck {
private static final String face[] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King"};
private static final String suit[] = {"Spade", "Club", "Diamond", "Heart"};
private static final Card deckOfCards[] = new Card [52];

public Deck(){
int suitCount = 0;
int faceCount = 0;
int faceValue = 0;
for(int i = 1; i < deckOfCards.length; i++){
deckOfCards[i].setSuit(suit[suitCount]);
deckOfCards[i].setFace(face[faceCount], faceValue);
suitCount++;
faceCount++;
faceValue++;
if(suitCount == 3){
suitCount = 0;
}
if(faceCount == 12){
faceCount = 0;
}
if(faceValue == 13){
faceValue = 1;
}
}
}

正如你所看到的,我已经在数组中定义了脸部和套装,并且我想将它们分配给正确的值,但是当我尝试运行它时,我在 deckOfCards[i].setSuit(suit[suitCount]); 行收到 nullPointerException

我似乎无法弄清楚为什么它给我这个错误,当我调试它时,它似乎初始化了所有字段,但是当它到达那里时它崩溃了。

最佳答案

您初始化了数组,但没有初始化其中的元素。您可以在循环中执行此操作:

deckOfCards[i] = new Card();
deckOfCards[i].setSuit(suit[suitCount]);

关于java - 尝试使用字段数组作为参数时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41070913/

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