我正在做一个任务。我已经掌握了我需要做的基础知识,但由于某种原因,compareTo 没有在一组示例输入上正确排序。第一组输入正确排序并返回正确的值,但第二组重新排列,但不排序。基本上我有一个对象牛,它有时间和吃掉的一些花。我想把这些东西拿来排序,先按时间,最短时间优先,然后按吃的花,数量最多的优先。所以如果我有 3 头奶牛,1 和 10、2 和 5、2 和 7。我会对它们进行排序,第一、第三和第二。希望这是有道理的。我不确定为什么 Collection.sort 没有按预期工作......但希望有人能引导我朝着我做错的正确方向前进。
到目前为止,这是我的代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Flowers {
public static void main(String[] args) {
ArrayList<Cow> list = new ArrayList<Cow>();
Scanner input = new Scanner(System.in);
final int numOfCows = Integer.parseInt(input.next());
int totalFlowers = 0;
// Fills the list with the cows attributes (time and flowers destroyed)
for (int i = 0; i < numOfCows; i++) {
int theTime = Integer.parseInt(input.next());
int theFlowers = Integer.parseInt(input.next());
final Cow theCow = new Cow(theTime, theFlowers);
list.add(theCow);
}
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
for (int k = 0; k < list.get(i).time; k++)
for (int j = i + 1; j < list.size(); j++) {
totalFlowers += (list.get(j).flowers * 2);
}
}
System.out.println(totalFlowers);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
input.close();
}
public static final class Cow implements Comparable<Cow> {
public final int time;
public final int flowers;
public Cow(final int theTime, final int theFlowers) {
time = theTime;
flowers = theFlowers;
}
@Override
public int compareTo(Cow other) {
int compared = 1;
if (this.time < other.time) {
compared = -1;
} else {
if (this.flowers > other.flowers) {
compared = -1;
}
}
return compared;
}
@Override
public String toString() {
return String.format("Time:%d Flowers: %d", time, flowers);
}
}
}