I’m having problems storing the high score of the game with multiple players who each have a different name and score. no matter the players score, the code outputs that they beat the high score. the maximum number of rounds is 15. the problem seems to be the high score variable resets when going through the full loop again and doesn’t keep the previous high score for a new player. the entire game function is inside a do while loop.
String highScorer = " ";
int highScore = 15;
if (score < highScore) {
highScorer = name;
highScore = score;
System.out.println("Congrats! You beat the high score!");
}
//output person with high score
System.out.println("The high score belongs to " + highScorer + " at " + highScore + " tries!");
The code doesn’t store the high score consistently when looping through the do while loop for multiple players
>Solution :
It seems like you are reinitializing the highScore variable to 15 inside the loop, which means that it will always reset to that value at the start of each iteration. To fix this, you should initialize highScore before the loop and then update it only if a new high score is achieved. Here’s an example of how you can modify your code:
int highScore = 15; // Initialize high score outside the loop
String highScorer = " ";
do {
// Code for playing the game and getting the player's name and score
if (score < highScore) {
highScorer = name;
highScore = score;
System.out.println("Congrats! You beat the high score!");
}
} while (/* condition for playing another round */);
// Output person with high score after the loop
System.out.println("The high score belongs to " + highScorer + " at " + highScore + " tries!");