Hi all,
I'm writing a card game but I can't seem to set the cards in the deck. I'm getting a runtime exception error, whether I first try to set the suit or the rank. Here's my code:

Card.java

public class Card
{
	private String suit;
	private int rank;
	
	Card()
	{

	}

	public Card(String suit,int rank)
	{
		this.suit=suit;
		this.rank=rank;
	}
	
	public void setSuit(String suit)
	{
		this.suit=suit;
	}

	public void setRank(int rank)
	{
		this.rank=rank;
	}

Hearts.java

public class Hearts
{
	public static void main (String [] args)
	{
		Player [] players = new Player [3];
		Card [] deck = new Card [51];
		boolean finish=false;
		int roundNo=1;
		
		System.out.println("hmm");

		while (finish==false)
		{
			boolean roundComplete=false;
				
			while (roundComplete==false)
			{
				System.out.println("h111");
				boolean continueGame=true;

				for (int i=0;i<deck.length;i++)
				{
					System.out.println(i);
					if ((i>=0)&&(i<13))
					{
						deck[i].setRank(i);
							
						deck[i].setSuit("d");
						System.out.println("yay");
					}

I'm having trouble in the loop, where I'm setting the suit and rank. Can anyone spot what's wrong with the code?

Cheers,

I believe it's because you never initialise your array. Try replacing lines 26 - 28 in your hearts class with this:

deck[i] = new Card("d", i);

Thanks, that solved the original problem! Now I got a second one, a null pointer exception. What I'm trying to do is deal the cards to the players.

Hearts.java

//deal cards
				for (int i=0;i<51;i++)
				{
					players[0].addCard(deck[i].getSuit(),deck[i].getRank());
					players[1].addCard(deck[i].getSuit(),deck[i].getRank());
					players[2].addCard(deck[i].getSuit(),deck[i].getRank());
					players[3].addCard(deck[i].getSuit(),deck[i].getRank());
				}

Player.java

public class Player
{
	private String name;
	private int number;
	private int score;
	private Card [] hand=new Card [12];
	
	public Player()
	{
		
	}

	public void addCard(String suit,int rank)
	{
		for(int i=0;i<hand.length;i++)
		{
			if (hand[i]==null)
			{
				hand[i].addCard(suit,rank);
				break;
			}
		}	
	}

Any ideas on this?

Cheers,

Your null pointer exception is the result of the number of items declared for your array. You want to have 4 players but only declared enough space for 3 of them. Change lines 5 and 6 in hearts.java to:

Player [] players = new Player [4];		
Card [] deck = new Card [52];
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.