用java写一个学生类,对总成绩降序排列输出并打印名次

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Student implements Comparable{
    public String name;
    public int xuehao, mingci;
    public double a1, a2, a3;
 
    public Student(int xuehao, String name, double a1, double a2, double a3) {
        this.xuehao = xuehao;
        this.name = name;
        this.a1 = a1;
        this.a2 = a2;
        this.a3 = a3;
    }
 
    public double sum() {
        return (this.a1 + this.a2 + this.a3);
    }
 
    @Override
    public int compareTo(Student o) {
        double o1Sum = this.sum();
        double o2Sum = o.sum();
        return o1Sum == o2Sum ? 0 : o1Sum > o2Sum ? 1 : -1;
    }
    
    public static void main(String[] args) {
        List students = new ArrayList();
        students.add(new Student(20160001,“学生一”,85,72,95));
        students.add(new Student(20160002,“学生二”,87,88,92));
        students.add(new Student(20160003,“学生三”,20,60,56));
        students.add(new Student(20160004,“学生四”,99,94,59));
        students.add(new Student(20160005,“学生五”,100,100,100));
        System.out.println(“初始顺序(姓名,总分)”);
        for (Student p : students) {
            System.out.println(p.name + " | " + p.sum());
        }
        
        Collections.sort(students);
        
        System.out.println(“排序后(姓名,总分,名次)”);
        int index = 0;
        for (int i = 0; i < students.size(); i++) {
            Student p = students.get(i);
            if(i == 0 || p.sum() > students.get(i-1).sum()){
                index ++ ;
            }
            System.out.println(p.name + " | " + p.sum() + " | " + index);
        }
    }
 
}

你可能感兴趣的:(JAVA)