首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >堆栈搜索导致堆栈溢出

堆栈搜索导致堆栈溢出
EN

Stack Overflow用户
提问于 2012-03-13 04:33:38
回答 1查看 127关注 0票数 1

我试图通过输入搜索卡,将搜索卡的值(颜色和等级)与手中的当前牌进行比较,并在找到匹配的情况下,输出匹配的卡并改变当前玩家的“情绪”,从而尝试搜索“一手牌”(一个队列)。如果没有找到匹配项,并且还没有搜索到整个手牌,则将当前卡出队,在手背排队,然后再次运行该方法。如果已经搜索了整个手牌(返回到手牌的第一张牌),则将返回一个“虚拟牌”。我的问题是,如果找不到匹配卡,则会出现一个StackOverflowError。我不知道这是从哪里来的,但我认为这与卡的入队/出队和方法的递归性(接近尾声)有关。如果有人能帮忙,我将不胜感激。如果你需要更多的代码或者更多的信息,尽管问。

新代码:

代码语言:javascript
复制
(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);
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-13 04:41:00

我认为你应该有这样的东西:

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9674401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档