2016-11-05 249 views
0
/* Assume as precondition that the list of players is not empty. 
* Returns the winning score, that is, the lowest total score. 
* @return winning score 
*/ 
public int winningScore() { 
    Player thePlayer = players.get(0); 
    int result = thePlayer.totalScore(); 
    for (int i = 0; i < players.size(); i++){ 
     int p = players.get(i).totalScore(); 
     if (p < result) { 
      result = players.get(i).totalScore(); 
     } 
    } 
    return result; 
} 

/* Returns the list of winners, that is, the names of those players 
* with the lowest total score. 
* The winners' names should be stored in the same order as they occur 
* in the tournament list. 
* If there are no players, return empty list. 
* @return list of winners' names 
*/ 
public ArrayList<String> winners() { 
    ArrayList<String> result = new ArrayList<String>(); 

    for (int i = 0; i < players.size(); i++) 
     if (!players.isEmpty()) 
      return result; 
} 

因爲它在註釋中聲明,所以我試圖在winners方法中返回winningScore()結果,以便返回贏家/贏家名稱。將數值從一種方法返回到另一種方法

我設法只返回所有的獲獎者,但是如果它應該從winningScore()方法調用或者不是有點困惑?

我明白我當前的代碼是不正確的贏家

在正確的方向推任何/提示,將不勝感激!謝謝!

+0

那麼它看起來像你應該調用'winningScore()'從'贏家()'方法入手...如'int scoreToMatch = winningScore();'。然後循環所有球員,看看哪些球員*得分*。 –

+0

@Jon Skeet謝謝! – copernicon1543

回答

1

你想要做的就是在你的獲勝者方法中找到所有獲勝分數的選手對象。

  • 要做到這一點,您需要首先通過致電 您的winningScore方法來計算獲勝分數。
  • 接下來,您會發現所有玩家對象的totalScore等於以前計算的獲勝分數 。你想要返回這些。

然後爲獲獎者的方法生成的代碼應該是這樣的:

public ArrayList<String> winners() { 
    ArrayList<String> result = new ArrayList<String>(); 

    int winningScore = winningScore(); 

    for (int i = 0; i < players.size(); i++) 
     if (players.get(i).totalScore() == winningScore) 
      result.add(players.get(i).getName()) 

    return result; 
} 

如果要簡化代碼,你可以通過循環使用ArrayList迭代器這樣的替代for循環,因爲你不使用索引變量i

for (Player player : players) { 
    if (player.totalScore() == winningScore) 
     result.add(player.getName()) 
} 
+0

謝謝!爲了清楚起見,這將在玩家列表中循環播放,並將totalScore與winningScore方法進行比較,然後將獲勝者名稱添加到ArrayList result = new ArrayList ()? – copernicon1543

+0

要返回一個空列表,你只需要調用返回結果? – copernicon1543

+0

感謝您的評論。現在它將玩家名稱(通過玩家對象中的getName()方法)添加到結果列表中。通常我會建議返回一個ArrayList 而不是一個字符串列表,因爲你可以在播放列表中做更多的事情,而不僅僅是使用字符串列表。 – biro

相關問題