# Null pointer exception a

Printable View

• 08-15-2011, 10:34 PM
TaxpayersMoney
Null pointer exception a
Here's the code. The problem first occurs at "deck[Counter].setSuit(CHDS);"

Code:

import java.util.Scanner;

public class Game {

public static void main(String[] args){

Game game=new Game();
game.playGame();

}

private int numPlayers;
private Card[] deck = new Card[51];
private Card.suits trumps;
private Player players[]= new Player[4];
Scanner input=new Scanner(System.in);
private int Counter=0;

public Game(){

// Initialize deck
for(Card.suits CHDS : Card.suits.values()){

for(int n=1;n<14;n++){

deck[Counter].setSuit(CHDS);
deck[Counter].setValue(n);
Counter++;

}

}

// Sets trumps
trumps=Card.suits.C;
System.out.println("Trumps are clubs.");

// Code to get user to input number of players
System.out.println("Enter the desired number of players");
numPlayers=input.nextInt();

}

public void playGame(){

}

}

And the Card class:

Code:

import java.util.Random;

public class Card {

private Random rand=new Random();
private suits suit;
private int value;

public enum suits{C, H, D, S;}

public Card(suits theSuit, int theValue){
suit=theSuit;
value=theValue;
}

public void dealHand(){

}

public Card[] shuffleDeck(Card theDeck[]){
Card tempDeck[]= new Card[51];
for(int n=0;n<51;n++){
rand.nextInt(52);
}
return tempDeck;
}

public suits getSuit() {
return suit;
}

public void setSuit(suits suit) {
this.suit = suit;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

}

• 08-15-2011, 10:57 PM
Iron Lion
Code:

for(int n=1;n<14;n++)
This looks like your problem. Remember that Java starts counting at 0, so 13 will be out of range.
• 08-15-2011, 11:05 PM
TaxpayersMoney
Quote:

Originally Posted by Iron Lion
Code:

for(int n=1;n<14;n++)
This looks like your problem. Remember that Java starts counting at 0, so 13 will be out of range.

Thanks for the reply. I thought that in the case of that particular for loop java would start counting at 1 continue to 13 and then stop.
• 08-16-2011, 12:20 AM
Norm
Its not the number of times thru the loop, its that the index goes past the end of the array.
for(int i=12; i < arraySize; i++)
i can start anywhere. It does not have to start at 0. Yet the array's first element is at index 0. This code would skip the elements in the first part of the array.
• 08-16-2011, 12:28 AM
Junky
It is not the loop that is the problem. It is the fact that the array is full of nulls and not Card objects as they are never created. Thus when trying to call the setSuit method on a null reference causes the NPE.
• 08-16-2011, 12:37 AM
Norm
Whoops. Ran off at the mouth without having the OP post the Full text of the error message.

OP - Please post the full text of the error message when you get errors. It saves a lot of false starts.