我如何按降序排序?

时间:2014-03-10 23:09:55

标签: java algorithm sorting collections arraylist

我们需要创建两个类:GirlScoutCheck和CookieAnalyzerCheck。我们需要获得用户输入 - 询问他们每个女孩的名字,直到他们输入失控。然后我们向他们询问每个女孩出售的饼干盒的数量,然后分别为每个女孩添加饼干盒并乘以3.50。这是总收入。然后我们根据总收入按降序对它们进行排序。我做了几乎所有事情。我只需要帮助排序和打印已排序的信息。任何人都可以帮我完成这个吗?谢谢。

package Pcs;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class CookieAnalyzerCheck {

public static void main(String args[]) {
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    String name = "";
    ArrayList al = new ArrayList();

    do {
        Scanner kb = new Scanner(System.in);
        System.out.println("Please enter the name of each"
                + " girl Scout, or \"RUNAWAY\" "
                + "to exit.");
        name = kb.nextLine();
        if (!name.equalsIgnoreCase("runaway")) {
            System.out.println("Enter the number of Thin Mints sold");
            int ThinMints = kb.nextInt();
            System.out.println("Enter the number of Caramel Delights sold");
            int CaramelDelights = kb.nextInt();
            System.out.println("Enter the number of Lemonades sold");
            int Lemonades = kb.nextInt();
            System.out.println("Enter the number of ThanksALot sold");
            int ThanksALot = kb.nextInt();
            System.out.println("Enter the number of MangoCremes sold");
            int MangoCremes = kb.nextInt();
            GirlScoutCheck ba = new GirlScoutCheck(name, ThinMints, CaramelDelights, Lemonades, ThanksALot, MangoCremes);
            al.add(ba);
            System.out.println(""); //makes output easier to read
            System.out.println();
        }
    } while (!name.equalsIgnoreCase("runaway"));


    GirlScoutCheck thisBA = (GirlScoutCheck) al.get(0);

    double maxBalance = thisBA.totalIncome;
    String maxName = thisBA.name;

    for (int i = 1; i < al.size(); i++) {
        thisBA = (GirlScoutCheck) al.get(i);
        if (thisBA.totalIncome > maxBalance) {
            //we have a new winner, so save the..
            maxBalance = thisBA.totalIncome;
            maxName = thisBA.name;

          int a= al.size();




            }
        }
    }


}



package Pcs;

import java.util.Collections;



public class GirlScoutCheck implements Comparable {
public String name;
public int ThinMints;
public int CaramelDelights;
public int Lemonades;
public int ThanksALot;
public int MangoCremes;
public int totalCookies;
public double totalIncome;

public GirlScoutCheck(String nm, int tm,int cd, int lem, int tal, int mc){
    name = nm;
    ThinMints = tm;
    CaramelDelights = cd;
    Lemonades = lem;
    ThanksALot = tal;
    MangoCremes = mc;
    totalCookies = ThinMints+CaramelDelights+Lemonades+ThanksALot+MangoCremes;
    totalIncome = totalCookies*3.50;
}

public int totalCookies(){
    return totalCookies;

}

public double totalIncome(){
    return totalIncome;

}
  public int compareTo(Object done){
   GirlScoutCheck b= (GirlScoutCheck)done;
   if (totalIncome>b.totalIncome){
       return 1;
   }
       else if(totalIncome<b.totalIncome)  {
           return -1;

       }
       else{
           return 0; 
   }


}


public String getName(){
        String nameParts[] = name.split(" ");
    String first = nameParts[0];
    String last = nameParts[1];

    return String.format(last + "," + first);
}








@Override
public String toString() {
    return "girlScoutCheck [name=" + getName() + ", ThinMints=" + ThinMints
            + ", CaramelDelights=" + CaramelDelights + ", Lemonades="
            + Lemonades + ", ThanksALot=" + ThanksALot + ", MangoCremes="
            + MangoCremes + ", totalCookies=" + totalCookies + "]"+ System.lineSeparator()+ " (total income for Thin Mints is $" +
                    ThinMints*3.50+ ") ( total income for Caramel Delights is $" +
                    CaramelDelights*3.50+ ") total income for Lemonades is $" +
                    Lemonades*3.50+ ")( total income for MangoCremes is $" +
                    MangoCremes*3.50+ ") (total income for ThanksALot is $" +
                    ThanksALot*3.50+ ")"+System.lineSeparator() ;

}


}

1 个答案:

答案 0 :(得分:1)

我认为您在main方法中遗漏了一些内容:

  • 您的变量nf 从未使用过
  • 由于您要对GirlScoutCheck进行排序,我建议您使用TreeSet来存储它们,而不是ArrayListTreeSet是始终排序的元素集合(here is its javadoc entry)。

理想情况下,您应该声明并初始化该容器,如下所示:

final Set<GirlScoutCheck> al = new TreeSet<>();
  • 您应该始终关闭流和任何外部资源。 id est :在离开Scanner方法之前关闭main

您可以使用Try-With-Resource语法执行此操作,如下所示:

try (final Scanner kb = new Scanner(System.in)) {
    do {
        // your stuff
        kb.nextLine();
    } while (!name.equalsIgnoreCase("runaway"));
}

顺便说一下,在阅读另一位女孩的名字之前,您可能需要消费最后一次换行:我建议您在重新输入之前简单地拨打kb.nextLine(); do/while循环(正如我在上面的 Try-With-Resource 示例中所做的那样)。

基本上,您的主要方法可能只是:

final Set<GirlScoutCheck> al = new TreeSet<>();

try (final Scanner kb = new Scanner(System.in)) {
    do {
        // your stuff
        kb.nextLine();
    } while (!name.equalsIgnoreCase("runaway"));
}

// from now on, al will contain all the GirlScoutCheck's ordered "as you want"

for (final GirlScoutCheck gsc : al) {
    System.out.println(gsc);
}

而且......就是这样!


现在,实际上,要实现此“自动排序”,我们需要声明如何比较您的GirlScoutCheck。您正在做GirlScoutCheck实施Comparable:)

的正确做法

但是,您应该指定您正在实施Comparable<GirlScoutCheck>。因此,您覆盖的compareTo方法的签名变为:

public int compareTo(final GirlScoutCheck other)

而不是:

public int compareTo(final Object other);

您也可以这样简化:

@Override
public int compareTo(final GirlScoutCheck o) {
    return (int) (o.totalIncome - this.totalIncome);
}

最后一点: 确保已排序的集合(例如equals)表现良好,需要与TreeSet保持一致。
资料来源:Implementing compareTo - JavaPractices

因此,您还应该为equals实现hashcodeGirlScoutCheck仅使用totalIncome字段(以保持一致)使用compareTo实施)。别担心,你的IDE可能会为你做:) 无论如何,我也可以。所以这就是:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    long temp;
    temp = Double.doubleToLongBits(this.totalIncome);
    result = (prime * result) + (int) (temp ^ (temp >>> 32));
    return result;
}

@Override
public boolean equals(final Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final GirlScoutCheck other = (GirlScoutCheck) obj;
    if (Double.doubleToLongBits(this.totalIncome) != Double.doubleToLongBits(other.totalIncome)) {
        return false;
    }
    return true;
}

<强> TL; DR

只是...

  • 将该段代码推送到您的GirlScoutCheck班级
  • 用我给你的那个替换它的compareTo方法,
  • 请务必将其设为Comparable<GirlScoutCheck>,而不仅仅是Comparable
  • 按我的建议修改main方法...

一切都应该运作良好;)