排序

eviljordan 2012-11-24 10:17:04
期末,每个学生都有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名?
...全文
111 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
eviljordan 2012-11-25
  • 打赏
  • 举报
回复
引用 2 楼 tsyj810883979 的回复:
省去了set,get方法。。。 可以使用下面代码测试: Java code? 12345 List<Student> students = new ArrayList<Student>(); Collections.sort(students); for(Student stu : students.subList(0, 5)) { ……
你Interface里面是compareTo方法和toString方法呀? compareTo方法不是很懂,能解释下吗
涛涛_2009 2012-11-25
  • 打赏
  • 举报
回复
省去了set,get方法。。。 可以使用下面代码测试:
List<Student> students = new ArrayList<Student>();
		Collections.sort(students);
		for(Student stu : students.subList(0, 5)) {
			System.out.println(stu);
		}
涛涛_2009 2012-11-25
  • 打赏
  • 举报
回复
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 + "]";
	}
	
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧