将值从一种方法返回到另一种方法 [英] Returning a value from one method to another method

查看:82
本文介绍了将值从一种方法返回到另一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/* 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()结果,以便它返回中奖者的姓名.

As it states in the comments, I am trying to return the winningScore() result in the winners method so it returns the the winner/winners names.

我设法只退回了所有获奖者,但是是否应该从winningScore()方法中调用,我有点困惑?

I have managed to only return all of the winners but am a little confused if it should be calling from the winningScore() method or not?

我了解我当前的代码对获奖者不正确

I understand my current code is incorrect for winners

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

Any push/hint in the right direction would be appreciated! Thanks!

推荐答案

您要做的是在获胜者方法中查找所有具有获胜得分的玩家对象.

What you want to do is to find all player objects with the winning score in your winners method.

  • 为此,您需要先通过致电来计算获胜分数 您的winningScore方法.
  • 接下来,您将找到所有totalScore等于 先前计算的获胜分数.您要退货.
  • To do this you need to first calculate the winning score by calling your winningScore method.
  • Next you find all player objects whose totalScore equals the previously calculated winning score. You want to return those.

您的获奖者方法的结果代码将如下所示:

The resulting code for your winners method would then look like this:

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:

If you want to simplify the code, you can substitute the for loop by a loop using the ArrayList iterator like this, since you do not use the index variable i:

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

这篇关于将值从一种方法返回到另一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆