【问题标题】:Returning a value from one method to another method将值从一种方法返回到另一种方法
【发布时间】:2017-03-19 02:29:23
【问题描述】:
/* 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;
}

正如它在 cmets 中所述,我试图在获胜者方法中返回winningScore() 结果,以便返回获胜者/获胜者的姓名。

我设法只返回了所有的获胜者,但我有点困惑是否应该从 winsScore() 方法调用它?

我知道我当前的代码对于获胜者来说是不正确的

任何正确方向的推动/提示将不胜感激!谢谢!

【问题讨论】:

  • 看来您应该从winners() 方法调用winningScore() 以...例如int scoreToMatch = winningScore();。然后遍历所有玩家并查看哪些玩家拥有该分数。
  • @Jon Skeet 谢谢!

标签: java string arraylist return


【解决方案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())
}

【讨论】:

  • 谢谢!为了清楚起见,这会在玩家列表中运行一个循环,并将 totalScore 与winningScore 方法进行比较,然后将获胜者姓名添加到 ArrayList result = new ArrayList() ?
  • 要返回一个空列表,你会调用返回结果吗?
  • 感谢您的评论。现在它将玩家名称(通过玩家对象中的 getName() 方法)添加到结果列表中。通常我会建议返回一个 ArrayList 而不是一个字符串列表,因为你可以用播放器列表做更多的事情而不是只用字符串列表。
  • 如果玩家列表为空,for循环将不会运行,这会导致结果列表为空,因为不会将玩家名称添加到结果列表中
  • 再次感谢您的帮助(包括编码和逻辑解释)。多亏了你,方法才奏效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多