我试图遍历所有玩家和
1>输出一行 2 - ;创建一个对象
基于某些条件。但是我收到了Stackoverflow错误。
public void refuteSuggestion(Weapon w, Character c, int currentPlayerNumber) {
for (Player p : game.getPlayers()) {
if(currentPlayerNumber != 6) {
if (p.getNum() == currentPlayerNumber + 1) {
Set<Card> cardSet = new HashSet<>();
cardSet.addAll(p.getPlayerCards());
Card card = (Card) getRandomObject(cardSet);
System.out.println(card.getName(0));
} else {
refuteSuggestion(w, c, currentPlayerNumber + 1);
}
}
else{
refuteSuggestion(w, c, 0);
}
}
System.out.println("No one refuted...");
}
答案 0 :(得分:1)
不确定你在这里尝试做什么,但是你是在同一个方法中调用方法,这是一个无限循环。因此堆栈溢出错误。
在你的Else条件中,你只是改变currentPlayerNumber的值,所以只需这样做而不是在更改currentPlayerNumber之后调用相同的函数。
如果逻辑更容易理解,你也可以创建一个单独的函数来处理你的代码。
public void refuteSuggestion(Weapon w, Character c, int currentPlayerNumber) {
for (Player p : game.getPlayers()) {
if(currentPlayerNumber != 6) {
if (p.getNum() == currentPlayerNumber + 1) {
nextFunction(p);
} else {
currentPlayerNumber += 1;
}
}
else{
currentPlayerNumber = 0;
}
}
System.out.println("No one refuted...");
}
public void nextFunction(Player p){
Set<Card> cardSet = new HashSet<>();
cardSet.addAll(p.getPlayerCards());
Card card = (Card) getRandomObject(cardSet);
System.out.println(card.getName(0));
}