Nanda Ardianto Nanda Ardianto - 4 months ago 19
Java Question

Stack Overflow error while looping

I am trying to loop through all the players and

1> Output a line

2> Create an object

based on certain conditions. But I am getting a Stackoverflow error.

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...");
}

Answer

Not sure what you are trying to do here, but you are calling the method from within the same method which is an endless loop. Hence the stack overflow error.

In your Else conditions, you are only changing the value of currentPlayerNumber so just do that instead of calling the same function after changing the currentPlayerNumber.

You may also create a separate function to handle your code inside if logic if it makes easier to understand.

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