1

I am writing a homework assignment that creates a full deck of 52 cards. I am having a slight problem at line 18.

hearts[x].setSuit("Hearts");

Here is the rest of the code:

public class FullDeck 
{
public static void main(String[] args)
{
    //Creates four arrays for each deck
    Card[] hearts = new Card[13];
    Card[] clubs = new Card[13];
    Card[] spades = new Card[13];
    Card[] diamonds = new Card[13];



    //Fills the hearts deck

    for(int x = 0; x < hearts.length; ++x)
    {

        hearts[x].setSuit("Hearts");
        hearts[x].setValue(x+1);
        System.out.println("The " + hearts[x].getRank() + " of " + hearts[x].getSuit());
    }


 }
}

The client class for the Card type:

public class Card
{
private String suit;
private int value;
private String rank;
public String getSuit()
{
  return suit;
}
public int getValue()
{
  return value;
}
public String getRank()
{
  return rank;
}
public void setSuit(String s)
{
  suit = s;
}
public void setValue(int v)
{
  final int LOW = 1;
  final int HIGH = 13;
  if(v >= LOW && v <= HIGH)
     value = v;
   else
     value = LOW;
  if(value == 1)
    rank = "Ace";
  else
    if(value == 11)
      rank ="Jack";
    else
      if(value == 12)
         rank = "Queen";
      else
         if(value == 13)
           rank = "King";
         else
           rank = Integer.toString(value);
 }  
} 

If I could have a detailed explanation please as to what exactly is going wrong would be very appreciated :). I'm new to coding in java as well so any tips from veterans out there will be kindly noted, thank you!

captaindex
  • 11
  • 2
  • 1
    Summary: add "hearts[x] = new Card();" before "hearts[x].setSuit("Hearts");" for the nullpointerException to go away. Explaination: Issue is with initializing of all the object arrays viz. hearts, clubs etc. Initializing the arrays viz. Card[] hearts = new Card[13]; only creates an array with the Card class type. Before accessing the object viz. hearts[x].setSuit("Hearts"); you will have to initialized the object like hearts[x] = new Card(); for each of them in the loop. – ininprsr Apr 17 '17 at 06:24

0 Answers0