簡體   English   中英

將值從一種方法返回到另一種方法

[英]Returning a value from one method to another method

/* 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()結果,以便它返回一個或多個Winner名稱。

我設法只返回了所有獲獎者,但是是否應該從winningScore()方法中調用,我有點困惑?

我了解我當前的代碼對獲獎者不正確

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

您要做的是在獲勝者方法中找到所有具有獲勝得分的玩家對象。

  • 為此,您需要首先通過調用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迭代ArrayList一個循環替換for循環,因為您不使用索引變量i

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM