【问题标题】:how do i finish sorting this in descending order?我如何按降序完成排序?
【发布时间】:2014-04-14 07:56:17
【问题描述】:

我们需要创建两个类:GirlScoutCheck 和 CookieAnalyzerCheck。我们需要获得用户输入——询问他们每个女孩的名字,直到他们输入 runaway。然后我们向他们询问每个女孩卖出的饼干盒的数量,然后分别将每个女孩的饼干盒相加并乘以 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() ;

}


}

【问题讨论】:

  • 能否请您概述一下您正在处理的问题?目前还不是很清楚,是什么问题。
  • 您似乎忘记在尝试排序的地方分享您的代码。通常它只是调用适当的排序方法(在数组或集合上),可能使用自定义比较器(这可能是必要的,因为您想对递减排序)。
  • @Warlord- 我不知道在 CookieAnalyzerCheck 类结束时排序的方法。

标签: java algorithm sorting collections arraylist


【解决方案1】:

我认为您在 main 方法中遗漏了一些东西:

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

理想情况下,您应该按如下方式声明和初始化该容器:

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

您可以简单地使用Try-With-Resource 语法来做到这一点,如下所示:

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

顺便说一句,在阅读另一个女孩的名字之前,您可能需要使用最后一个换行符:我建议您在重新输入您的 @987654335 之前直接致电 kb.nextLine(); @ 循环(就像我在上面的 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&lt;GirlScoutCheck&gt;。因此,您要覆盖的 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

因此,您还应该为您的GirlScoutCheck 实现equalshashcode仅使用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;博士

只是……

  • 将该片段代码推入您的GirlScoutCheck 类,
  • 用我给你的方法替换它的 compareTo 方法,
  • 确保实现Comparable&lt;GirlScoutCheck&gt; 而不仅仅是Comparable
  • 按照我的建议修改main 方法...

一切都应该运行良好;)

【讨论】:

  • 谢谢!你太有帮助了!我完成了我的任务!:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多