Results 1 to 6 of 6
Thread: Null pointer exception a
- 08-15-2011, 10:34 PM #1
Null pointer exception a
Here's the code. The problem first occurs at "deck[Counter].setSuit(CHDS);"
And the Card class:Java 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(){ } }
Java 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 #2
Senior Member
- Join Date
- Nov 2010
- Posts
- 210
- Rep Power
- 3
This looks like your problem. Remember that Java starts counting at 0, so 13 will be out of range.Java Code:for(int n=1;n<14;n++)
- 08-15-2011, 11:05 PM #3
- 08-16-2011, 12:20 AM #4
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 #5
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 #6
Similar Threads
-
Null Pointer Exception HELP!?
By 2wyked in forum New To JavaReplies: 3Last Post: 04-04-2011, 01:41 AM -
Null Pointer exception (Again !!)
By mobosecomin in forum New To JavaReplies: 6Last Post: 03-29-2011, 05:04 PM -
Null pointer exception?
By coffee in forum New To JavaReplies: 4Last Post: 08-03-2009, 03:22 AM -
Null Pointer Exception
By demiser55 in forum New To JavaReplies: 1Last Post: 09-22-2008, 06:33 PM -
getting a null pointer exception
By Rjava in forum XMLReplies: 4Last Post: 07-16-2008, 05:56 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks