Background: my assignment was to write a program that uses linked list to keep track of cards in a card game (war). So I wrote 4 programs: card.java, deckofcards.java, hand.java, war.java(driver). card holds basic info. When adding to a linked list of the cards I use a method called setLast:
nextCard=null;
public card(String a, String b)
{
hand=a;
suit=b;
}
public void setLast(card c)
{
if(nextCard==null)
{
nextCard = c;
}
else
{
nextCard.setLast(c);
}
}
then in deckofcards.java:
card deck, dealt;
public deckofcards()
{
rand = new Random();
dealt = new card("0","0"); //null card place holders
first = new card("0","0");
numcards = 52;
shuffle();
}
public card dealCard()
{
card c=new card("0","0");
if(first!= null)
{
c = first;
first = first.nextCard;
c.nextCard = null;
if(dealt.toString().compareTo("00")==0)
{
dealt = c;
}
else
{
dealt.setLast(c);
}
numcards--;
}
else
{
System.out.println("Deck: ran out of cards");
}
return c;
}
so deckofcards generates 52 randomly(supposed to anyway, but thats a different question) ordered cards and hands deals them to instances of hand.java in war.java
hand.java:
card cards;
int numcards;
public void getCard(card c)
{
System.out.println("In hand.java,getCard");
if (numcards==0)
{
cards = c;
numcards++;
}
else
{
cards.setLast(c);
}
}
and war.java:
players = new hand[numplayers];
for(int i=0;i<numplayers;i++)
{
players[i] = new hand();
}
deck = new deckofcards();
int i=0;
while(i<52)
{
int ii=0;
if((ii<numplayers)&&(i<52))
{
players[ii].getCard(deck.dealCard());
i++;
ii++;
}
else
{
ii=0;
}
}
output:
In hand.java,getCard
In hand.java,getCard
Exception in thread “main” java.lang.StackOverflowError
at card.setLast(card.java:125)
at card.setLast(card.java:125)
at card.setLast(card.java:125)
at card.setLast(card.java:125)
at card.setLast(card.java:125)
at card.setLast(card.java:125)
at card.setLast(card.java:125)
//repeated 1000s of times…
Of course I only provided the snippet of code I believe is causing the problem I can provide the whole code upon request.
Your list has a loop somewhere, i.e. “A->B->C->D->B”. Is there a reason you are using “null card placeholders” instead of the value null? I notice setLast is checking for the value ‘null’ instead of ’00’ for your null placeholder, but without seeing all the code it’s hard to tell where your list gets a loop at.