Question: Please can someone help given the class GameEntry , and ScoreBoard.The ScoreBoard saves the entries in an ascending order, so we have to shift the
Please can someone help given the class GameEntry , and ScoreBoard.The ScoreBoard saves the entries in an ascending order, so we have to shift the elements when we add or remove an element. Assume we do not want to save the entries sorted in order to avoid shift operations, however the array in the board should not have null values between the elements.
a) Rewrite the methods add(e ), remove(i) without using any loops( so they have better
performance).
Please rewrite these functions and show that it still works well.
public class GameEntry {
private String name; private int score; public GameEntry(String name, int score) { this.name = name; this.score = score; }
/**Returns the name field **/ public String getName() { return name; }
/**Returns the score field **/ public int getScore() { return score; }
/** Returns the String representation of this entry **/ @Override public String toString() { return "(" + name + ", " + score + ")"; }
}
public class Scoreboard {
private int numEntries = 0; private GameEntry[] board;
public Scoreboard(int capacity) { board = new GameEntry[capacity]; }
public void add(GameEntry e) { int newScore = e.getScore(); // is the new entry e really a high score? if (numEntries < board.length || newScore > board[numEntries - 1].getScore()) { if (numEntries < board.length) // no score drops from the board numEntries++; // so overall number increases // shift any lower scores rightward to make room for the new entry int j = numEntries - 1; while (j > 0 && board[j - 1].getScore() < newScore) { board[j] = board[j - 1]; // shift entry from j-1 to j j--; // and decrement j } board[j] = e; // when done, add new entry } }
/** Remove and return the high score at index i. */ public GameEntry remove(int i) throws IndexOutOfBoundsException { if (i < 0 || i >= numEntries) throw new IndexOutOfBoundsException("Invalid index: " + i); GameEntry temp = board[i]; // save the object to be removed for (int j = i; j < numEntries - 1; j++) // count up from i (not down) board[j] = board[j + 1]; // move one cell to the left board[numEntries - 1] = null; // null out the old last score numEntries--; return temp; // return the removed object }
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
