将值从一个方法返回到另一个方法

时间:2016-11-05 09:09:22

标签: java string arraylist return

/* 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;
}

正如评论中所述,我试图在获胜者方法中返回winsScore()结果,以便返回获胜者/获胜者名称。

我设法只返回所有获胜者,但是如果它应该是使用winsScore()方法调用的话,我有点困惑吗?

我理解我的当前代码对于获奖者来说是不正确的

任何正确方向的提示/提示都将受到赞赏!谢谢!

1 个答案:

答案 0 :(得分:1)

您要做的是在获胜者方法中找到所有具有获胜分数的玩家对象。

  • 要做到这一点,您需要先致电计算获胜分数 你的winsScore方法。
  • 接下来,您将找到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;
}

如果要简化代码,可以使用这样的for迭代器通过循环替换ArrayList循环,因为您不使用索引变量i:< / p>

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