2015年7月31日 星期五

Java作業練習01:學生成績排名

完成 Student 類別,依總分由大排到小,總分相同比英文,英文相同比數學,數學相同比名字,名字相同則亂數決定

Student 類別
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Student implements Comparable<Student> {

    String name;
    int eng;
    int math;
    int sum;

    public Student(String name, int eng, int math) {
        this.name = name;
        this.eng = eng;
        this.math = math;
        this.sum = eng + math;
    }

    @Override
    public String toString() {
        return name + " " + eng + " " + math + " " + sum;
    }

    @Override
    public int compareTo(Student o) {
        if (this.sum > o.sum) {
            return -1;
        } else if (this.sum == o.sum && this.eng > o.eng) {
            return -1;
        } else if (this.eng == o.eng && this.math > o.math) {
            return -1;
        } else if (this.math == o.math && this.name.compareTo(o.name)<0) { //名字字串比對
            return -1;
        } else if (this.name.compareTo(o.name)== 0){
            return (int) Math.random()*10;
        }return 1;
    }
}

StudentTest 主程式
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class StudentTest {

    public static void main(String[] args) {
       Set<Student> set =new TreeSet<>();
       set.add(new Student("Tom", 100, 90)); //190
       set.add(new Student("Amy", 95, 100)); //195
       set.add(new Student("Joe", 95, 95)); //190
       set.add(new Student("Lee", 100, 90)); //190
       
       //依總分由大排到小,總分相同比英文,英文相同比數學,數學相同比名字,名字相同則亂數決定 
       System.out.println("成績排行");
       int rank=0;
       for(Student stu:set){
           rank++;
           System.out.println(rank+". "+stu.toString());
       }

    }

}

顯示結果


code
Student
StudentTest

沒有留言:

張貼留言