期末,每个学生都有3门课的成绩:语文、数学、英语。先按总分从高到低排序,如果两个同学总分相同,再按语文成绩从高到低排序,如果两个同学总分和语文成绩都相同,那么规定学号小的同学排在前面,这样,每个学生的排序是唯一确定的。 
任务:先根据输入的3门课的成绩计算总分,然后按上述规则排序,最后按排名顺序输出前5名学生的学号和总分。
样例输入
8
80 89 89
88 98 78
90 67 80
87 66 91
78 89 91
88 99 77
67 89 64
78 89 98
样例输出
8 265
2 264
6 264
1 258
5 258应该怎样求前5名?

解决方案 »

  1.   

    class Student implements Comparable<Student> {
    int sno;
    float chinese;
    float math;
    float english;
    float sum; public Student() {
    } public Student(int sno, float _chinese, float _math, float _english) {
    this.sno = sno;
    this.chinese = _chinese;
    this.math = _math;
    this.english = _english;
    this.sum = _chinese + _math + _english;
    } @Override
    public int compareTo(Student o) {
    if(this.sum > o.sum) {
    return 1;
    } else if(this.sum == o.sum) {
    if(this.chinese > o.chinese) {
    return 1;
    } else if(this.chinese == o.chinese) {
    if(this.sno > o.sno) {
    return 1;
    } else {
    return -1;
    }
    } else {
    return -1;
    }
    } else {
    return -1;
    }
    } @Override
    public String toString() {
    return "Student [sno=" + sno + ", chinese=" + chinese + ", math="
    + math + ", english=" + english + ", sum=" + sum + "]";
    }

    }
      

  2.   

    省去了set,get方法
    可以使用下面代码测试:
    List<Student> students = new ArrayList<Student>();
    Collections.sort(students);
    for(Student stu : students.subList(0, 5)) {
    System.out.println(stu);
    }
      

  3.   

    你Interface里面是compareTo方法和toString方法呀?
    compareTo方法不是很懂,能解释下吗