寻找以下问题的帮助以下可比较的方法,想要打印从我的Hockey Player ArrayList得分的最大目标值。我无法成功地为每个循环存储值以将其传递给可比较的方法。有什么建议我做错了吗?
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));
}
答案 0 :(得分:1)
我普遍同意“使用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
将调用toString
函数作为Player
函数返回的maximum
类。类似的东西(我给出的例子,使用你在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;
}
不确定你想要在那里完成什么