In you constructor you have passed null as a variable
public Deck(int numCards) {
this.createDeck(numCards, 4, null);
}
within your method createDeck you then try to use that variable
private void createDeck(int numCards, int numSuits, String[] cardRanks) { //<---cardRanks is null at this point
deck = new ArrayList<Card>();
cardUsed = new ArrayList<Card>();
if ((numCards % numSuits) > 0) return;
for (int i=0; i < numSuits; i++) {
for(int j=1; j <= (numCards / numSuits); j++) {
deck.add(new Card(new Suit(i), cardRanks[j-1], cardRanks, j));
}
}
}
When you write cardRanks[j-1]
you are trying to access the "inside" of cardRanks. If cardRanks is null, i.e. doesn't exist, then it can't access the inside and a NullPointerException
is its only option. Java understandably complains.
In english what you are telling the program to do (when cardRanks is null) is to take the j-1 element of 'nothing'. This clearly is meaningless and a NullPointerException
is how the compiler tells you
Creating arrays of strings that are not null
String[] stringArray=new String[10]; //creates an array big enough to hold 10 Strings
At present the stringArray holds 10 nulls
stringArray[0]="hi"; //enter first element
stringArray[1]="hi again"; //enter second element
stringArray[2]=""; //empty string is not the same as null
Now the first 3 elements are non null, the remaining 7 remain null
you could of course create your strings in a loop or in any way you see fit
Creating a class that doesn't need to take its fields in a constructor
public class SomeClass {
String[] someStringArray={"hello", "i'm just fine as I am"}; //creates an array of strings, 2 entries
int someNumber;
public SomeClass(int someNumber){
//this constructor leaves someStringArray alone, its fine as it is
this.someNumber=someNumber;
}
public SomeClass(int someNumber,String[] someStringArray){
//this constructor changes someStringArray
this.someNumber=someNumber;
this.someStringArray=someStringArray;
}
}