【问题标题】:How to create a method contains an array that compare the elements to get the highest one?如何创建一个方法包含一个比较元素以获得最高元素的数组?
【发布时间】:2012-02-26 23:11:55
【问题描述】:

我有一个名为 Player 的类,包含以下实例变量:

private String name, position;
private int numGames, numGoalsScored, numGoalsConceded;

该类也有两个构造函数,一个具有名称和位置作为参数,另一个是复制构造函数。 我被要求创建一个名为Team 的类,这个类应该包含许多控制Player 类的方法。其中一种方法是bestPlayer(),这个方法应该得到性能最好的播放器,计算为在播放器类中写的getPerformance();方法。

我的问题是:如何创建一种方法来获得最佳球员?
我编写了以下代码,但遗憾的是它不起作用:

/* Get the best player */
public Player bestPlayer()
{
    if (playerNum == 0)
    {
        System.out.println("Error: Empty team!");
    }
    double max = 0;
    int index = 0;
    for ( int i = 0; i<playerNum; i++ ){

        if(playerList[i].getPerformance() > max) {
            max = playerList[i];
        }
    }

    return playerList[index];
}

我不断收到“不兼容的类型”错误!

【问题讨论】:

    标签: java arrays loops


    【解决方案1】:

    我看到一个与max = playerList[i] 不兼容的类型,假设 playerList 是一个 Player 类型的数组。你怎么能把一个球员分配给一个替身?除此之外,我还发现该方法还有其他一些问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      相关资源
      最近更新 更多