简体   繁体   中英

Null Point Exception Error with simple card class

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);
    }

Evidently, you aren't adding 52 Card instances to your array (you add 4 for each of 12 iterations, 12 * 4 = 48 != 52). So when you loop over the entire array, some of the values will inevitably be null (remember that arrays of objects initially contain only null s). Looping until i < 13 should fix this.

The problem lies here:

        temp[i+13] = new Card("Club", i + 1);

It will never be 12, which is why you get your nullpointer exception.

问题是你只是将temp数组填充到索引50(11 + 39),第二个循环尝试访问索引51.第一个循环的上限应该是13而不是12。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM