Skip to main content

Implementing own class.

1 reply [Last post]
arpen
Offline
Joined: 2011-11-09
Points: 0

Hello, I am doing an exercise for school which involves implementing a class of your own. And in this case a class describing a card deck. This is what I got so far:

public class CardDeck {

private Card[] cards; //the cards

private int current; //index for the next card

private static Random rand = new Random();

/** creates a deck of cards */

public CardDeck(){

cards = new Card[52]; //array

for(int suit = Card.SPADES; suit <= Card.HEARTS; suit++){

for(int rank = Card.SPADES; rank <= Card.HEARTS; rank++){

cards[current] = new Card(suit, rank);

current++;

}

}

}

public void shuffle(){

for(int i=51;i>0 ; i--){

int nbr = 0+rand.nextInt(i+1);

Card temp = cards[i];

cards[i] = cards[nbr];

cards[nbr] = temp;

}

}

public boolean moreCards(){

if(current == 0){

return false;

}else{

return true;

}

}

public Card getCard(){

current -=1;

return cards[current];

}

}

And here is my main program I am trying to run it in:

public class Card {

public static void main(String[] args) {

int ok = 0;

for(int i = 0; i<1000000; i++){

CardDeck deck = new CardDeck();

deck.shuffle();

int j = 1;

boolean cont = true;

while(deck.moreCards() && cont ){

Card c = deck.getCard();

if(c.getRank() != j){ //** gives the error message*/

j++;

cont = true;

}else{

cont = false;

}

if(j > 3){

j = 1;

}

}

if(cont){

ok +=1;

}

}

System.out.println((double) ok/1000000);

}

}

When I try it out in my main program I get a NullPointerException when trying to compare the ranks of cards. I'm all out of ideas now, so please help!

One other thing, the main program draws a card and says one, then does the same til it has counted up to three. IF it can do that for the whole deck of cards it's +1 to the ok, then I check the probability of that happening.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
bishow
Offline
Joined: 2011-11-20
Points: 0

Where you got error while you compling the code.

Trace me full error.