Skip to main content

Beginner Help - NullPointerException

1 reply [Last post]
jmdingess
Offline
Joined: 2012-06-03
Points: 0

I understand what a NullPointerException is, but I am not sure why I am getting one. As stated in the title I am an absolute beginner to Java, and I am teaching myself using an online tutorial. I use cmd to compile my programs using Jdk.1.7.0. Anyway the problem is that the following code gives me the following exception:

class Card {
public String suit;
public int rank;


public Card() {
suit = "Hearts";
rank = 13;
}

public Card(String suit, int rank) {
this.rank = rank;
this.suit = suit;
}

public String Read() {
String strRank = "Error";
switch (rank) {
case 1: strRank = "Ace";
break;
case 2: strRank = "Two";
break;
case 3: strRank = "Three";
break;
case 4: strRank = "Four";
break;
case 5: strRank = "Five";
break;
case 6: strRank = "Six";
break;
case 7: strRank = "Seven";
break;
case 8: strRank = "Eight";
break;
case 9: strRank = "Nine";
break;
case 10: strRank = "Ten";
break;
case 11: strRank = "Jack";
break;
case 12: strRank = "Queen";
break;
case 13: strRank = "King";
break;
}
return(strRank + " of " + suit);
}

}

class Deck {
public Card[] deck;
public Deck() {
for (int i=0;i<4;i++) {
for (int x=1;x<=13;x++) {
switch (i) {
case 0: deck[((i*13)+x)] = new Card("Hearts",x);
break;
case 1: deck[((i*13)+x)] = new Card("Clubs",x);
break;
case 2: deck[((i*13)+x)] = new Card("Diamonds",x);
break;
case 3: deck[((i*13)+x)] = new Card("Spades",x);
break;
}
}
}
}


}

public class Testing {
public static void main(String[] args) {
Deck NewDeck = new Deck();
System.out.println(NewDeck.deck[23].Read());
}
}

Exception in thread "main" java.lang.NullPointerException
at Deck.(Testing.java:57)
at Testing.main(Testing.java:75)

Line 57 is the start of the class Deck's Constructor, and line 75 is the end.

Can anyone please tell me what I am doing wrong?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
phil1234
Offline
Joined: 2011-07-15
Points: 0

You need to instantiate your array before you can fill it with values:
public Card[] deck = new Card[arraySize];
arraySize would probably be 52 in your case.