I am looking for a solution to Absolute JAVA 5th Ed, by Walter Savitch, Project
ID: 665831 • Letter: I
Question
I am looking for a solution to Absolute JAVA 5th Ed, by Walter Savitch, Project #7 from Chapter 10 on page 644.
Write a class that keeps track of the top five high scores that could be used for a video game. Internally, the class should store the top scores in a data structure of your choice (the most straightforward way is to use arrays). Each entry consists of a name and a score. The data stored in memory should be synchronized with a text file for persistent storage. For example, here are the contents of a sample file where Ronaldo has the highest score and Pele has the third highest score:
Ronaldo
10400
Didier
9800
Pele
9750
Kaka
8400
Cristiano
8000
The constructor should test if the file exists. If it does not exist, then the file should be created with blank names for each of the players and a score of 0. If the file does exist, then the data from the file should be read into the class’s instance variables.
Along with appropriate constructors, accessors, and mutators, add the following methods:
• void playerScore(String name, int score): Whenever a game is over, this method is called with the player’s name and final score. If the name is one of the top five, then it should be added to the list and the lowest score should be dropped out.
If the score is not in the top five, then nothing happens.
• String[] getTopNames() : Returns an array of the names of the top players, with the top player first, the second best player second, etc.
• int[] getTopScores() : Returns an array of the scores of the top players, with the highest score first, the second highest score second, etc.
Explanation / Answer
import java.util.*; import java.io.*; class TopScores{ // yes // this should never change after your class is created, so make it final private final String filename; // magic numbers, bad private final int TOP_COUNT = 5; // assign in constructor // String[] player = new String[5]; // array to hold players // int[] playerScore = new int[5]; // array for scores // also, choose names consistent with method names private final String[] names; private final int[] scores; // do NOT pass scores here, you're confusing yourself public TopScores1() { this("topscores.txt"); } public TopScores1(String filename) { this.filename = filename; this.names = new String[TOP_COUNT]; this.scores = new int[TOP_COUNT]; // note, scores are all 0 // just load up the strings for(int i = 0; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.