gpt4 book ai didi

java - 对数组进行排序并获取第 3 个最大的元素

转载 作者:行者123 更新时间:2023-12-02 00:35:04 25 4
gpt4 key购买 nike

我是初学者java程序员。我有这样的作业:写一个静态方法,方法中的参数是一个 Drink 数组。该方法返回 3 个最大的酒精饮料数组元素。

我的问题是:是否有我写的更短的解决方案?

    public static void alcoholMax(AlcoholDrink[] t){
// sort the AlcoholDrink[] t
Arrays.sort(t, new Comparator<AlcoholDrink>() {
// here I try sorting the elements by their alcohol value
@Override
public int compare(AlcoholDrink o1, AlcoholDrink o2) {
int at1 = (int)o1.getAlcohol(); // get the alcohol value
int at2 = (int)o2.getAlcohol(); // get the alcohol value
if(at1>at2)
return -1;
else if(at1<at2 )
return 1;
return 0;
}
});
// get the 3 largest element of the sorted array
double t0 = t[0].getAlcohol();
double t1 = t[1].getAlcohol();
double t2 = t[2].getAlcohol();
// check, 1st > 2nd > 3rd, if this not true, return with null reference
if(t0>t1 && t1>t2)
System.out.println(t[0] + "\n" + t[1] + "\n" + t[2]);
else
System.out.println("null");
}

public static void main(String[] args){
AlcoholDrink[] t = new AlcoholDrink [8];
// new AlcoholDrink( String Name, String Stripping, int price, double alcohol)
// these are hungarian wines :). If somebody curious for the languange
t[0] = new AlcoholDrink("Kék Portói", "0.75 l", 1200, 20.5);
t[1] = new AlcoholDrink("Kék Oportó", "0.75 l", 1100, 10.5);
t[2] = new AlcoholDrink("Tokaji Asszú", "0.75 l ", 1600, 14.5);
t[3] = new AlcoholDrink("Egri Bikavér", "0.75 l", 1500, 23.5);
t[4] = new AlcoholDrink("Egri Leányka", "0.75 l", 1100, 8.5);
t[5] = new AlcoholDrink("Egri Merlot", "0.75 l", 1700, 18.5);
t[6] = new AlcoholDrink("Egri Medina", "0.75 l", 900, 16.5);
t[7] = new AlcoholDrink("Törley Talisman", "0.75 l", 750, 4.5);

alcoholMax(t);
// It is always return with "null"

最佳答案

如果您的 getAlcohol() 方法返回 double,那么您不应该将其转换为 int,这会导致精度损失。此外,您可以自动比较 double ,而不是自己进行比较,如下所示:

Arrays.sort(t, new Comparator<AlcoholDrink>() { 
// here I try sorting the elements by their alcohol value
@Override
public int compare(AlcoholDrink o1, AlcoholDrink o2) {
return o1.getAlcohol().compareTo(o2.getAlcohol());
}
});

您还可以使您的 Alcohol 类实现 Comparable 接口(interface),如 this 所示。例子。

最后,如果您想坚持使用自己的代码,您可能需要考虑对比较方法返回的值进行更改,如下所示:

 @Override
public int compare(AlcoholDrink o1, AlcoholDrink o2) {
int at1 = (int)o1.getAlcohol(); // get the alcohol value
int at2 = (int)o2.getAlcohol(); // get the alcohol value
if(at1>at2)
return -1;
else if(at1<at2 )
return 1;
return 0;
}

我目前无法测试代码,但您可能会以升序方式对数组进行排序。

关于java - 对数组进行排序并获取第 3 个最大的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8020749/

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