scoreboard添加或删除分数并对其进行排序

问题描述 投票:0回答:1

我正在尝试向当前分数添加和删除分数,因此,在打印输出时,我希望将较早的分数添加到+1,然后将其加总并打印新分数。这不起作用,我尝试了很多选择,我该如何解决这个问题?

我试图在名称和数组中添加名称和分数,然后进行排序,如何解决该问题?

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;                         
    }
  }
java game-development
1个回答
0
投票

添加(GameEntry e):将游戏条目e插入高分数组。如果数组已满,则仅当e的分数高于集合中的最低分数时才添加e,在这种情况下,e用最低分数替换条目。但是我们需要弄清楚放置e的位置。

public void add(GameEntry e) {
int newScore = e.getScore();
if (numEntries == maxEntries) { // the array is full
if (newScore <= entries[numEntries-1].getScore())
return; // the new entry, e, is not a high score in this case
}
else // the array is not full
numEntries++;
// Locate the place that the new (high score) entry e belongs
int i = numEntries-1;
for ( ; (i >= 1) && (newScore > entries[i-1].getScore()); i--)
entries[i] = entries[i - 1]; // move entry i one to the right

entries[i] = e; // add the new score to entries
}

remove(int i):删除并返回数组索引i中的游戏条目e。如果索引i在entrys数组的边界之外,则此方法将引发异常;否则,此方法将引发异常。否则,将更新entrys数组以删除索引i处的对象,并且将先前存储在索引处高于i的所有对象移至上方,以填充删除的对象。

public GameEntry remove(int i) throws IndexOutOfBoundsException {
if ((i < 0) || (i >= numEntries))
throw new IndexOutOfBoundsException( "Invalid index: " + i);
GameEntry temp = entries[i]; // temporarily save the object to be removed
for (int j = i; j < numEntries - 1; j++) // count up from i (not down)
entries[j] = entries[j+1]; // move one cell to the left
entries[numEntries -1 ] = null; // null out the old last score
numEntries--;
return temp; // return the removed object
 }
© www.soinside.com 2019 - 2024. All rights reserved.