Write the Java code for performing add(e) and remove(e) methods for the Scoreboa
ID: 3586653 • Letter: W
Question
Write the Java code for performing add(e) and remove(e) methods for the Scoreboard class, as shown below, except this time, don’t maintain the game entries in order. Assume that we still need to keep n entries stored in indices 0 to n-1. You should be able to implement the methods without using any loop, so that the number of steps they perform does not depend on n. Create a Driver class to test your code.
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();
if(numEntries < board.length || newScore > board[numEntries -1].getScore()){
if (numEntries < board.length)
numEntries++ ;
int j= numEntries -1;
while( j> 0 && board[j-1].getScore() < newScore) {
board[j] = board[j-1];
j--;
}
board[j] = e;
}
}
public GameEntry remove(int i) throws IndexOutOfBoundsException {
if (i< 0 || i >= numEntries)
throw new IndexOutOfBoundsException ("Invalid index: " + i);
GameEntry temp =board[i];
for(int j=i ; j< numEntries-1; j++)
board[j] = board[j+1];
board[numEntries-1] = null;
numEntries --;
return temp;
}
Explanation / Answer
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();
if(numEntries < board.length) {
board[numEntries++] = e;
}
}
public GameEntry remove(int i) throws IndexOutOfBoundsException {
if (i< 0 || i >= numEntries)
throw new IndexOutOfBoundsException ("Invalid index: " + i);
GameEntry temp =board[i];
if (i == numEntries-1) {
board[i] = null;
}
else {
board[i] = board[numEntries-1];
board[numEntries-1] = null;
}
numEntries--;
return temp;
}
}
For driver class full question is needed.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.