Nanda Ardianto Nanda Ardianto - 4 months ago 20
Java Question

Stack Overflow query

I'm not sure why I am getting stack overflow here. I'm just trying to go through each player and if im at the end, I loop back to the start. So like it's for cluedo and its going through the players in a clock wise fashion. It's doing it with the getNum. refuteSuggestion is supposed to check if the Weapon and the character matches a players card in their hand. the currenPlayerNumber is the number of the currentPlayer, player 1 will be 1. for every Player in the game, if the currentPlayerNumber is not 6 (the end of the player counts (gonna change this to <= 6 instead) check if the player's number is the currentPlayerNumber + 1 (next player) if it is, do stuff, else, recurse. If the currentPlayerNumber == 6, recurse from the start. Keep checking until no players have the card.

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