1. 程式人生 > >用java寫一個學生類,對總成績降序排列輸出並列印名次

用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);
        }
    }
 
}