2012-03-12 227 views
1

我正在尝试通过输入搜索卡来搜索“手牌”(队列),将搜索卡的值(颜色和等级)与手中的当前卡进行比较,以及如果找到匹配,则输出匹配卡并改变当前玩家的“心情”。如果没有找到匹配并且整个手牌未被搜索到,则当前卡片出列,排在手牌后面,并且该方法再次运行。如果整个手牌已被搜索(返回到第一张牌的手牌),那么将返回一张“虚拟牌”。 我的问题是,如果找不到匹配的卡片,则会出现StackOverflowError。我不知道这是从哪里来的,但我认为这与卡片的入队/出队和方法的递归性(结束)有关。如果任何人都可以提供帮助,我将不胜感激。如果你需要更多的代码或更多的信息,请问。堆栈搜索导致堆栈溢出

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); 
     } 
    } 
} 
+0

你肯定'counter'不应该是一个方法参数,而不是一个方法变量? – 2012-03-12 20:38:01

+0

为什么不使用List(或者如果顺序无关紧要,就是Set)和它的'contains()'和'remove()'方法? – 2012-03-12 20:39:31

+0

'计数器'被用作表示该方法当前正在使用哪张牌。当该方法运行时,它被初始化为1(对于第一张卡片)。我不认为它应该是一个参数,因为每次调用该方法时都必须以相同的方式开始。我们不能使用列表,对不起。 – lollercopter 2012-03-12 20:40:34

回答

2

我认为你应该有这样的事情:

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); 
} 
+0

那么,这不是我所期望的,但有很多方法可以解决这个问题;) – Tim 2012-03-12 20:43:52

+0

哦,可能有更好的方法来处理这个问题,但这是我们可以进行的最小修改之一。没有代码的其余部分,很难说要做什么。 – 2012-03-12 20:44:56

+0

好的,我在我的顶端文章中更正了我的代码。我试图避免使用另一种方法来查看它是否可行。但是,在跟踪计数器并输入不匹配的情况下,计数器会在发生溢出之前增加到8500左右。测试如何检查'counter = cards.size()'(手的大小)不起作用? – lollercopter 2012-03-12 20:55:01