gpt4 book ai didi

java - 使用可比

转载 作者:行者123 更新时间:2023-12-01 10:14:31 24 4
gpt4 key购买 nike

正在寻求帮助解决以下遇到的问题,并使用下面的类似方法来打印我的曲棍球运动员数组列表中进球的最大值(value)。我无法成功存储 for every 循环中的值以将其传递给类似的方法。有什么建议我做错了什么吗?

public static Comparable maximum(Comparable first, Comparable second, Comparable third) {
if (first.compareTo(second) > 0) {
if (first.compareTo(third) > 0) {
return first;
}
return third;
} else if (second.compareTo(third) > 0) {
return second;
}
return third;
}

for (HockeyPlayer hp : hockeyPlayerList){
int first = ((HockeyPlayer) hp).getGoalsScored(); {
first = player1;
first = player2;
first = player3;
first = player4;
}
System.out.println("The largest string is: " + Driver.maximum(player1,player2,player3));
}

最佳答案

我总体上同意“use java.util.Collections.sort(hockeyPlayerList);”评论,但如果你必须实现你自己的最大...

假设您的最终目标是能够做到这一点:

System.out.println("The largest string is: " + Driver.maximum(player1,player2,player3));

该函数可能如下所示:

public class Driver {

...

public static Comparable maximum(Comparable... items)
{
if(items.length == 0)
{
return null; // no items to compare
}

Comparable currentMax = items[0];

for(Comparable item : items)
{
// Update currentMax only if next element is larger
currentMax = currentMax.compareTo(item) > 0 ? currentMax : item;
}

return currentMax;
}
}

在您的 Player 类中,您必须有一个 toString 函数,打印出有关播放器的有意义的信息(System.out.println 将为 maximum 函数返回的 Player 类的实例调用 toString 函数)。类似于(我给出的示例,使用您在 Player 函数中拥有的实际字段):

public class Player {

...
@Override
public String toString()
{
return this.getPlayerName() + ": " + this.getGoalsScored();
}
}

下面的代码片段也是没有意义的:

int first = ((HockeyPlayer) hp).getGoalsScored(); {
first = player1;
first = player2;
first = player3;
first = player4;
}

不确定你想在那里完成什么

关于java - 使用可比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35978462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com