繁体   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