Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

problem storing high score for a number guessing game in java

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading