我们被赋予了一项任务:按狗尾长度排序数组列表(双)如果两只或更多只狗具有相同的尾巴长度,请按名称排序我能够创建一个代码但是正确的结果呢……
我不确定这是否能解决你的问题,但你有一个问题
scan.nextLine();
在你的代码中,我不明白是否必须存在,因为据我所知它只等待你输入一些东西,然后它甚至不会将它保存在一个变量中。所以你可能会删除这一行(第12行)。
你试试这个吗?
import java.util.ArrayList; import java.util.Collections; public class Dog implements Comparable<Dog> { private double tailLength; private String name; public Dog(final double _tailLength, final String _name) { tailLength = _tailLength; name = _name; } @Override public String toString() { return "Dog [tailLength=" + tailLength + ", name=" + name + "]"; } @Override public int compareTo(final Dog o) { int res = Double.compare(tailLength, o.getTailLength()); if (res == 0) { res = name.compareTo(o.getName()); } return res; } public double getTailLength() { return tailLength; } public void setTailLength(final double tailLength) { this.tailLength = tailLength; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public static void main(final String[] args) { final ArrayList<Dog> dogs = new ArrayList<Dog>(); dogs.add(new Dog(2, "Dog D")); dogs.add(new Dog(2, "Dog A")); dogs.add(new Dog(5, "Dog C")); dogs.add(new Dog(4, "Dog A")); dogs.add(new Dog(3, "Dog A")); dogs.add(new Dog(3, "Dog B")); dogs.add(new Dog(1, "Dog A")); // Sort Dog by tailLength and name Collections.sort(dogs); final Scanner sc = new Scanner(System.in); while (true) { System.out.println("tailLength: "); final double inputTaillength = sc.nextDouble(); for (final Dog dog : dogs) { if (dog.tailLength == inputTaillength) { System.out.println(dog); } } } } }