模拟真实的成绩单(多门科目+总成绩),比冒泡更简单高效。
大概要求:
1、总成绩高的排在前面。
2、总成绩相同的情况下,语文成绩高的排在前面。
3、在总成绩,语文成绩都相同的情况下,数学成绩高的排在前面。
4、在成绩都相同的情况下,先输入的同学排在前面。
实体类:
1 public class Student{ 2 String name; 3 int rank ; 4 double cscore,mscore,escore; 5 6 public Student(String name, double cscore, double mscore, double escore) { 7 this.name = name; 8 this.cscore = cscore; 9 this.mscore = mscore; 10 this.escore = escore; 11 12 } 13 14 15 double sum() { 16 return (this.cscore + this.mscore + this.escore); 17 } 18 19 @Override 20 public String toString() { 21 return "Student{" + 22 "name='" + name + '\'' + 23 ", rank='" + rank + '\'' + 24 ", cscore=" + cscore + 25 ", mscore=" + mscore + 26 ", escore=" + escore + 27 ",sum=" + sum() + 28 '}'; 29 } 30 31 32 public double getCscore() { 33 return cscore; 34 } 35 36 public void setCscore(double cscore) { 37 this.cscore = cscore; 38 } 39 40 public double getMscore() { 41 return mscore; 42 } 43 44 public void setMscore(double mscore) { 45 this.mscore = mscore; 46 } 47 48 public String getName() { 49 return name; 50 } 51 52 public void setName(String name) { 53 this.name = name; 54 } 55 56 public double getEscore() { 57 return escore; 58 } 59 60 public void setEscore(double escore) { 61 this.escore = escore; 62 } 63 64 public int getRank() { 65 return rank; 66 } 67 68 public void setRank(int rank) { 69 this.rank = rank; 70 } 71 72 }
测试代码:
1 public class Test { 2 public static void main(String[] args) { 3 Student[] student = new Student[8]; 4 student[0] = new Student("学生一", 85, 72, 95); 5 student[1] = new Student("学生二", 87, 72, 93); 6 student[2] = new Student("学生三", 88, 73, 91); 7 student[3] = new Student("学生四", 99, 94, 56); 8 student[4] = new Student("学生五", 100, 100, 100); 9 student[5] = new Student("学生六", 35, 78, 83); 10 student[6] = new Student("学生七", 87, 66, 78); 11 student[7] = new Student("学生八", 87, 66, 78); 12 13 Comparator<Student> comparator = new Comparator<Student>() { 14 @Override 15 public int compare(Student o1, Student o2) { 16 if (o1.sum() == o2.sum()) { 17 if (o2.getCscore() == o1.getCscore()) { 18 if (o2.getMscore() == o1.getMscore()) { 19 return (int) (o2.getEscore() - o1.getEscore()); 20 } else { 21 return (int) (o2.getCscore() - o1.getCscore()); 22 } 23 } else { 24 return (int) (o2.getCscore() - o1.getCscore()); 25 } 26 } else { 27 return (int) (o2.sum() - o1.sum()); 28 } 29 } 30 }; 31 32 Queue<Student> queue = new PriorityQueue<>(comparator); 33 for (Student stu:student) { 34 queue.offer(stu); 35 } 36 37 int rank = 1; 38 while (queue.peek() != null) { 39 queue.peek().setRank(rank); 40 System.out.println(queue.poll()); 41 rank ++; 42 } 43 44 } 45 46 }
运行结果:
是的,有一个问题,就是学生七和学生八排名不对。参看PriorityQueue,先输入学生七,后输入学生八,按照队列的特点,先进先出,应该是先输出学生七,后输出学生八。在Student类中加入int priority属性,再compare()中判断,也不行。还有一个问题,如果我用ArrayList和LinkedList,排名并没有变化,不管是自身sort(),还是使用Collections.sort()。