I'm a beginner with Java, and I've been making test code to apply some of the concepts I read about. So, I wanted to create a class to describe playing cards. The card class contains fields describing both suite and value (1 - 13 for all 4 suites). This class was very simple to create, as you can see --
public class Card {
private String suite;
private int cardValue;
Card(String s, int cV){
this.suite = s;
this.cardValue = cV;
}
public String getSuite(){
return this.suite;
}
public int getCardValue(){
return this.cardValue;
}
}
I made another class to test this class, as well as add 52 cards to an array (I have another class that will deal with a 52 card deck, but that's not important in the context of my question here). This class, called CardTest, contains the main method. I created a for loop that appends everything to the deck array, however my problems occur when I want to loop through the deck and print out card values (suite and value). I receive a NullPointException error. Here is the cardTest class:
public class CardTest {
public static void main(String[] args){
Card[] temp = new Card[52];
for (int i = 0; i <12; i++){
temp[i] = new Card("Spade", i + 1);
temp[i+13] = new Card("Club", i + 1);
temp[i+26] = new Card("Diamond", i + 1);
temp[i +39] = new Card("Heart", i + 1);
}
for (int i = 0; i < 52; i++){
System.out.println(temp[i].getSuite());
}
}
}
I tried to search for issues regarding this type of error, but the only thing I've gathered is that there is an issue with the Card objects being set to a default "null" value, which yields the error on the method call.
Your for loop for creating cards is wrong you are only crating 12*4=48 cards, leaving temp[12], temp[25], temp[38] and temp[51] null, try
for (int i = 0; i <13; i++){
temp[i] = new Card("Spade", i + 1);
temp[i+13] = new Card("Club", i + 1);
temp[i+26] = new Card("Diamond", i + 1);
temp[i +39] = new Card("Heart", i + 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With