我们的任务是:
- 按狗的尾部长度对数组列表进行排序( double )
- 如果两只或更多的狗的尾部长度相同,则按名称对它们进行排序
我能够创建一个代码,但在第一次打印时没有显示正确的结果。我必须再次尝试排序才能真正发生。
我是编程新手,这让我很困惑。有任何想法吗?谢谢!
private void listDogs() {
boolean length = false;
for (int i = 0; i < dogs.size(); i++) {
length = true;
}
if (dogs.isEmpty()) {
System.out.println("Error: no dogs in register");
}else {
System.out.println("Please enter the tail lenght minimum: ");
double tailLength = scan.nextDouble();
scan.nextLine();
Collections.sort(dogs);
for (int i = 0; i < dogs.size(); i++) {
if (dogs.get(i).getTailLength() >= tailLength) {
System.out.println(dogs.get(i));
length = true;
}
}
if (length == false) {
System.out.println("Error: No dog is registered with this tail length.");
}
@Override
public int compareTo(Dog o) {
// TODO Auto-generated method stub
int compare = Double.compare(tailLength, o.tailLength);
if (compare == 0) {
compare = Double.compare(tailLength, o.tailLength);
}
if (compare == 0) {
compare = name.compareTo(o.name);
}
return compare;
}
最佳答案
我不确定这是否能解决您的问题,但您有一个
scan.nextLine();
在你的代码中,我不明白这是否必须存在,因为据我所知,它只等待你输入一些东西,然后它甚至不会将它保存在一个变量中。所以您可以删除这一行(第 12 行)。
关于java - 按 double 和字符串对数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54652314/