1. 程式人生 > 其它 >做一個排座的練習,要求成績好的優先排座,成績相同 身高矮的先排座 1.傳入學生個數,生成學生列表,成績取值範圍70-90身高120-140 2.傳入學生列表,返回排序後的學生列表

做一個排座的練習,要求成績好的優先排座,成績相同 身高矮的先排座 1.傳入學生個數,生成學生列表,成績取值範圍70-90身高120-140 2.傳入學生列表,返回排序後的學生列表

技術標籤:Java語言程式設計

1.首先我們寫一個學生類 裡面包括 姓名 成績 身高

程式碼如下

package Test;

/**
 * @author Administrator
 */
public class Student {
    String name;
    int achievement;
    int height;
    public Student(String name, int achievement, int height) {
        this.name = name;
        this.achievement = achievement;
        this.height = height;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAchievement() {
        return achievement;
    }

    public void setAchievement(int achievement) {
        this.achievement = achievement;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", achievement=" + achievement +
                ", height=" + height +
                '}';
    }
}

2.接著我們寫一個實現方法

根據輸入學生人數實現學生列表並存放在陣列中

public static ArrayList<Student> StudentList(int count) {
        ArrayList<Student> List = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            int achievement = (int) (Math.random() * 20 + 70);
            int height = (int) (Math.random() * 20 + 120);
            Student student = new Student("王" + i, achievement, height);
            List.add(student);
        }

        return List;
    }

3.寫好方法 裡面是沒有排序的陣列,寫一個

Comparator介面 用來根據成績和身高排序Comparator介面中有一個方法intcompare(To1, To2)。這個方法返回值是int型別,如果返回值小於0,說明比較結果是o1<o2,如果返回值等於0,說明比較結果是o1=o2,如果返回值大於0,則說明比較結果是o1>o2。

package Test;

import java.util.Comparator;

/**
 * @author Administrator
 */
public class StudentCompare implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        int a = o2.achievement - o1.achievement;
        if (a !=0 ) {
            return o2.achievement - o1.achievement;
        }else {
            return o1.height - o2.height;
        }

    }
}

4.在main方法裡面呼叫全部

 public static void main(String[] args) {
        List<Student> List = StudentList(2);
        System.out.println(List);
        Collections.sort(List, new StudentCompare());
        System.out.println(List);



    }

5.實現結果