We were given a task to:
- sort an array list by a dog's tail length (double)
- if two dogs or more have the same tail length, sort them by name
I was able to create a code BUT the correct results do not show up during the first print-out. I have to try again for the sorting to actually happen.
I'm very new to programming and this confuses me. Any ideas? Thanks!
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;
}
compareTomethod looks ok (except for the first 3 lines, remove them). You can write some tests to verify that it is working. The problem might be somewhere else, e.g. theif (dogs.get(i).getTailLength() >= tailLength) {looks potentially suspicious.