1. Engineering
  2. Computer Science
  3. override tostring for the class highscores it should return a...

Question: override tostring for the class highscores it should return a...

Question details

Override toString() for the class HighScores. It should return a String that contains all of the high scores in entries, formatted nicely. Note that toString is already implemented for the Score class. Then, write a driver program (in a file named Main.java) that thoroughly tests HighScores (i.e. add and remove scores from the list, add scores to an already full list, make sure the list remains sorted, etc).

Score.java

public class Score
{
protected String name; // name of the player earning this score
protected int score;
public Score(String n, int s)
{
name = n; score = s;
}
public String getName()
  {
  return name;
}
public int getScore()
{
  return score;
}
@Override public String toString()
{
  return "(" + name + ", " + score + ")";
}
}

HighScores.java

public class HighScores
{
    public static final int maxEntries = 10;
    protected int numEntries;
    protected Score[] entries;
    public HighScores()
    {
        entries = new Score[maxEntries];
        numEntries = 0;
    }
    public String toString()
    {
        //TODO
        return null;
    }
    // methods for updating the set of high scores go here
    public void add(Score s)
    {
        int newScore = s.getScore();
        if(numEntries == maxEntries)
        {
            if(newScore <= entries[numEntries - 1].getScore())
                return; // the new entry is not a high score
        }
        else
            numEntries++;
        int i = numEntries - 1;
        for (; (i >= 1) && newScore > entries[i - 1].getScore(); i--)
        {
            entries[i] = entries[i - 1]; // move entry[i - 1] one to the right
        }
        entries[i] = s;
    }
    public Score remove(int i) throws IndexOutOfBoundsException
    {
        if((i < 0) || (i >= numEntries))
        {
            throw new IndexOutOfBoundsException("Invalid index: " + i);
        }
        Score temp = entries[i];
        for(int j = i; j < numEntries - 1; j++)
        {
            entries[j] = entries[j + 1]; // move entries[j + 1] one to the left
        }
        entries[numEntries - 1] = null; // clear the previous final score
        numEntries--;
        return temp; // return the removed object
    }
}
Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution