- package exercises;
- import java.util.Arrays;
- import java.util.Set;
- import java.util.TreeSet;
- public class StudentSort {
- /** 三个学生英语,数学,语文成绩,总成绩排序输出
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Set<Student> student=new TreeSet<Student>();
- student.add(new Student("张三","A101",58,78,23));
- student.add(new Student("李四","A102",38,38,53));
- student.add(new Student("王五","B103",18,98,73));
- System.out.println(student);
- }
- }
- class Student implements Comparable<Student>{
- private String name;
- private String num;
- private int score[]=new int[3];
-
- public Student(String name, String num, int... socre) {
- super();
- this.name = name;
- this.num = num;
- this.score = socre;
- }
- @Override
- public int compareTo(Student s) {
- int sumScore1=0;
- int sumScore2=0;
- for(int i=0;i<this.score.length;i++){
- sumScore1+=this.score[i];
- sumScore2+=s.score[i];
- }
- //这里测试一下成绩,顺便看一下结果
- System.out.println("姓名:"+this.name+"总成绩为:"+sumScore1);
- System.out.println("姓名:"+s.name+"总成绩为:"+sumScore2);
- return sumScore2-sumScore1;//这里就不比较俩个人分数一样按名称字称字典排序了
- }
- @Override
- public String toString(){
- return "学生:"+name+" 学号:"+num+" 语文:"+Arrays.toString(score);
- }
- }
复制代码 |