While studying a tutorial i was asked to write a simple project that displays a deck and it's cards.Then i would create one and display it's cards.I was also said to have two classes,one for a single card,and one of the deck.So i decided that a good approach is to have an array of singleCards as a field of the deck.However something is not clear to me about the initialization of the array.I think that the no-arguments constructor is called.However something is wrong,so maybe you could help
The project:
Cards.java
package cards; public class Cards { public static void main(String[] args) { Deck pokemonCards = new Deck(10); pokemonCards.print(); } }
SingleCard.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cards; /** * * @author User */ public class SingleCard { private int rank; private String suit; private String name; SingleCard(int r, String s, String n) { rank = r; suit = s; name = n; } SingleCard() { rank = 0; suit = "No colour"; name = "No name"; } public String getName() { return name; } public int getRank() { return rank; } public String getSuit() { return suit; } public void printSuit() { System.out.println("Card " + name + "has " + suit + "suit"); } public void printRank() { System.out.println("Card " + name + "has " + rank + "rank"); } public void printName() { System.out.println("Card's name is " + name); } }
Deck.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cards; /** * * @author User */ public class Deck { private SingleCard[] deck; private int number; Deck(int numberOfCards) { deck = new SingleCard[numberOfCards]; number=numberOfCards; // for(int i=0 ; i<numberOfCards ; i++) // { // // } } public SingleCard getCard(int numberOfCard) { return deck[numberOfCard]; } void print() { for(int i=0 ; i<number ; i++) { deck[i].printName(); } } }
and the error
Exception in thread "main" java.lang.NullPointerException at cards.Deck.print(Deck.java:) at cards.Cards.main(Cards.java:) Java Result: 1