我试图通过输入搜索卡,将搜索卡的值(颜色和等级)与手中的当前牌进行比较,并在找到匹配的情况下,输出匹配的卡并改变当前玩家的“情绪”,从而尝试搜索“一手牌”(一个队列)。如果没有找到匹配项,并且还没有搜索到整个手牌,则将当前卡出队,在手背排队,然后再次运行该方法。如果已经搜索了整个手牌(返回到手牌的第一张牌),则将返回一个“虚拟牌”。我的问题是,如果找不到匹配卡,则会出现一个StackOverflowError。我不知道这是从哪里来的,但我认为这与卡的入队/出队和方法的递归性(接近尾声)有关。如果有人能帮忙,我将不胜感激。如果你需要更多的代码或者更多的信息,尽管问。
新代码:
(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);
}
}
}发布于 2012-03-13 04:41:00
我认为你应该有这样的东西:
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);
}https://stackoverflow.com/questions/9674401
复制相似问题