开发者

NullPointerException in Java code

开发者 https://www.devze.com 2023-04-12 15:28 出处:网络
I\'m learning Java and OOPS from oracle\'s website.I\'m doing this exercise. I\'m getting a null pointer exception when I run this code. Can someone explain to me what I\'ve done wrong?

I'm learning Java and OOPS from oracle's website. I'm doing this exercise.

I'm getting a null pointer exception when I run this code. Can someone explain to me what I've done wrong?

Card.java

public class Card {
 public enum Suits {
    SPADE,
    CLUB,
    DIAMOND,
    HEART       
  }

 public enum Ranks {
    Ace,
    DEUCE,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN,
    EIGHT,
    NINE,
    TEN,
    JACK,
    QUEEN,
    KING    
  }

    public Ranks rank;
    public Suits suit;

    public Card(Card.Ranks rank,Card.Suits suit) {
        this.rank=rank;
        this.suit=suit;
    }
}

Deck.java

import java.util.*;

public class Deck {
    public ArrayList&l开发者_开发问答t;Card> cards;
    private Card card;

    public Deck() {
        for(Card.Suits s: Card.Suits.values()) {
            for(Card.Ranks r:Card.Ranks.values()) {
                card=new Card(r,s);
                 cards.add(card);
            }
        }
    }
}

DisplayCards.java

public class DisplayCards {
    public static void main(String [] args) {
        Deck d=new Deck();
        for( Card c: d.cards) {
            System.out.println("Rank of the Card:"+c.rank.toString());
            System.out.println("Suit of the Card:"+c.suit.toString());  
        }
    }
}


public ArrayList<Card> cards; is never initialized, use public ArrayList<Card> cards = new ArrayList<Card>();


you did not create the new ArrayList for cards.

replace: public ArrayList<Card> cards; with public ArrayList<Card> cards = new ArrayList<Card>();


You need to initialize the list as well:

cards = new ArrayList<Card>();


Now I'm coming from more of a C# background, but it doesn't look like you initialized your ArrayList Cards. Try initializing it in the constructor with:

cards = new ArrayList<Card>();

and that should fix your problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号