gpt4 book ai didi

java - 引用 toString 时的 NPE

转载 作者:行者123 更新时间:2023-12-02 06:11:29 26 4
gpt4 key购买 nike

Error: Exception in thread "main" java.lang.NullPointerException
at Deck.toString(Deck.java:83)
at DeckDriver.main(DeckDriver.java:25)

我完全不明白为什么会收到此错误消息。 d.toString应该显示描述 Deck d 的 52 行代码。

甲板等级

import java.util.Random;
public class Deck
{
private Card[] deck;
private int nextCard;
Face face;
Suit suit;


/**
* Default Constructor
*
* <hr>
* Date created: Feb 17, 2014
*
*
*/
public Deck()
{
nextCard = 0;
deck = new Card[52];
int iCount;
for(iCount=0; iCount<52; iCount++)
{
Card c = new Card(iCount);
}
}


/**
* Copy Constructor
*
* <hr>
* Date created: Feb 17, 2014
*
*
* @param existingDeck
*/
public Deck(Deck existingDeck)
{
int i;
for(i=0;i<52;i++)
{
this.deck[i] = existingDeck.deck[i];
}
}

/**
* toString
*
* <hr>
* Date created: Feb 17, 2014
*
* <hr>
* @return
* @see java.lang.Object#toString()
*/
public String toString()
{
int iCount = 0;
String description = "";
for(iCount=0; iCount<52;iCount++)
{
description += deck[iCount].toString();
}
return description;
}

/**
* Shuffles the deck
*
* <hr>
* Date created: Feb 17, 2014
*
* <hr>
*/
public void shuffle()
{
Random r = new Random();
nextCard = 0;
int i;
for(i=0;i<52;i++)
{
int x = r.nextInt(52);
Card c = new Card();
c=deck[x];
deck[x]=deck[i];
deck[i]=c;
}
}

/**
* Deals individual card.
*
* <hr>
* Date created: Feb 17, 2014
*
* <hr>
* @return
*/
public Card dealACard()
{
Card c;
c=deck[nextCard];
nextCard++;

return c;
}

public String dealAHand(int handSize)
{
int i;
String hand="";
for(i=0;i==handSize;i++)
{
hand+="" + dealACard();
}
return hand;
}
}

DeckDriver 类

public class DeckDriver
{
public static void main(String[]args)
{
Deck d = new Deck();
System.out.print(d.toString()); //(this is the DeckDriver.main(DeckDriver.java:25))
}
}

最佳答案

默认构造函数中没有添加任何对象到数组中。您应该像在其他构造函数中一样初始化数组的每个字段。

关于java - 引用 toString 时的 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21838971/

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