-1

I am currently trying to make a java card game but am having trouble setting the card. I am taking in values such as 2H 3D 4S 5C 6H in the main function. I am trying to put these values into my Card class but when I try to set my rank I get a nullpointerexception error.

I am new to java programing and can not figure out why this is happening. Any suggestions? Am I not allowed to make an array of Cards?

public class Game {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int T = sc.nextInt();

    String[] player1arr = new String[5];
    String[] player2arr = new String[5];

    Card[] player1 = new Card[5];
    Card[] player2 = new Card[5];

    for(int i = 0; i < 5; i++){
        player1arr[i] = sc.next();
        char first = player1arr[i].charAt(0);
        int rank = Character.getNumericValue(first); //error
        player1[i].setRank(rank); 


    }

    for(int i = 0; i < 5; i++){
        player2arr[i] = sc.next();
        System.out.println(player2arr[i]);
    }  
  }
}

class Card{
    private int rank;
    private char suit;

    public int getRank(){
        return rank;
    }

    public void setRank(int r){
        rank = r;
    }
}
user081608
  • 1,093
  • 3
  • 22
  • 48
  • Please, post the error trace. Additionally, you are not creating Card instances in your array. You are just allocating memory for the array itself, but, with null Card objects in it. – Laerte Mar 25 '15 at 16:54

2 Answers2

2

When you create an array of objects, the array is initially filled with the default value of null. Call

cards[i] = new Card();

to initialize all the objects within the array :)

JTY
  • 1,009
  • 7
  • 13
2

You need to instantiate Cards in your main method.

for(int i = 0; i < 5; i++){
    player1arr[i] = sc.next();
    char first = player1arr[i].charAt(0);
    int rank = Character.getNumericValue(first); //error
    player1[i] = new Card();
    player1[i].setRank(rank); 


}
nomis
  • 2,545
  • 1
  • 14
  • 15