我是初學java程序員。 我有這樣的作業:寫一個靜態方法,在方法的參數中是一個Drink數組。該方法返回3個最大的酒精飲料數組元素。對數組進行排序並獲得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"
好吧,我知道......我必須要改變的,如果返回值:) :)案件+1 – blaces