I'm a beginner coder in a high school environment. I'm currently an AP Computer Science A student, and I have an in-class project to create a "fun" activity. I was trying to make a Card and Deck class in order to create different games with it, but I keep getting a NullPointerException run-time error from what I believe is in the Deck class. Can someone point me in the direction of why my code is behaving this way? The two classes are below. Thank you!
public class Card{
private String suit, color, name;
private int value;
public Card (){
suit = "Diamond";
color = "Red";
name = "One";
value = 1;
}
public Card(String n, String s, String c, int v){
suit = s;
color = c;
name = n;
value = v;
}
public String getSuit(){
return suit;
}
public void setSuit(String s){
suit = s;
}
public String getColor(){
return color;
}
public void setColor(String c){
color = c;
}
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
public int getValue(){
return value;
}
public void setValue(int v){
value = v;
}
}
public class Deck{
private Card[] decks;
public Deck(){
decks = new Card[52];
for (int i = 0; i<52; i++){
if(i<26){
decks[i].setColor("Red");
}
else{
decks[i].setColor("Black");
}
if(i<13){
decks[i].setSuit("Diamond");
decks[i].setValue(i+1);
}
else if (i<26){
decks[i].setSuit("Heart");
decks[i].setValue(i-13+1);
}
else if (i<39){
decks[i].setSuit("Spade");
decks[i].setValue(i-26+1);
}
else{
decks[i].setSuit("Clover");
decks[i].setValue(i-39+1);
}
}
for(int i=0; i<52; i++){
if(decks[i].getValue() == 1){
decks[i].setName("Ace");
}
else if (decks[i].getValue() == 11){
decks[i].setName("Jack");
}
else if (decks[i].getValue() == 12){
decks[i].setName("Queen");
}
else if (decks[i].getValue() == 13){
decks[i].setName("King");
}
else{
decks[i].setName(changeName(i));
}
}
}
public String changeName(int value){
if (value == 1)
return "One";
else if (value == 2)
return "Two";
else if (value == 3)
return "Three";
else if (value == 4)
return "Four";
else if (value == 5)
return "Five";
else if (value == 6)
return "Six";
else if (value == 7)
return "Seven";
else if (value == 8)
return "Eight";
else if (value == 9)
return "Nine";
else
return "Ten";
}
public void swap(Card[] d){
int rand = (int)(Math.random()*26 + 1);
int rand2 = (int)(Math.random()*26 + 27);
Card temp = decks[rand];
d[rand] = d[rand2];
d[rand2] = temp;
}
public void shuffle(){
for(int i = 0; i<26; i++){
swap(decks);
}
}
public Card getCard(int n){
return decks[n];
}
public int getValue(int n){
return decks[n].getValue();
}
public String getName(int n){
return decks[n].getName();
}
public String getSuit(int n){
return decks[n].getSuit();
}
public String getColor(int n){
return decks[n].getColor();
}
public Card[] getDeck(){
return decks;
}
}