Search code examples
javaqueuestack-overflow

Stack search causes stack overflow


I am trying to search a "hand of cards" (a queue) by inputting a search card, comparing the values (colour and rank) of the search card to the current card in the hand, and if a match is found, outputting the matching card and changing the "mood" of the current player. If no match is found and the entire hand has not been searched, then the current card is dequeued, enqueued at the back of the hand, and the method is run again. If the entire hand has been searched (leading back to the first card of the hand), then a "dummy card" is to be returned. My problem is that, if a matching card is not found, then a StackOverflowError appears. I do not know where this is coming from, but I presume it has to do with the enqueuing/dequeuing of the cards and recursiveness of the method (toward the end). If anyone can help, I would appreciate it. If you need more code or more info, just ask.

NEW CODE:

(at top of class)
int counter = 1;

....

/**
 * Method that checks a player's hand for matching cards
 * @param searchCard card to search for in player's hand
 * @return card in player's hand if found, dummy card otherwise
 */
public UnoCard getMatch(UnoCard searchCard) {
    UnoCard foundCard;
    UnoCard currentCard = cards.first();
    UnoCard noCard = new UnoCard('N', 0);

    //check if colours of cards match
    if (currentCard.getColour() == searchCard.getColour()) {
        //set mood, remove card from hand, and return matching card
        setMood("Colour");
        foundCard = currentCard;
        cards.dequeue();
        return foundCard;
    //check if ranks of cards match
    } else if (currentCard.getRank() == searchCard.getRank()) {
        //set mood, remove card from hand, and return matching card
        setMood("Rank");            
        foundCard = currentCard;
        cards.dequeue();
        return foundCard;
    //if no match is found
    } else {
        //check if end of hand has been reached
        if (counter == cards.size()) {
            //set mood and return dummy card
            setMood("No match");
            counter = 1;
            return noCard;
        } else {
            //place card at back of hand and search again with next card in hand
            counter++;
            System.out.println("Counter is: " + counter);
            cards.dequeue();
            cards.enqueue(currentCard);
            return getMatch(searchCard);
        }
    }
}

Solution

  • I think that you should have something like this:

    public UnoCard getMatch(UnoCard searchCard) {
        return getMatch(searchCard, 0);
    }
    
    private UnoCard getMatch(UnoCard searchCard, int counter) {
        //int counter = 0
        ... the rest of your code
    
        // Recursion at the end
        getMatch(searchCard, counter);
    }