成绩排序(内部排序)

题目描述:

用一维数组存储学号和成绩,然后,按成绩排序输出。

输入描述:

输入第一行包括一个整数n(1<=n<=100),代表学生的个数。接下来的n行每行包括两个整数p和q,分别代表每个学生的学号和成绩。

输出描述:

按照学生的成绩从小到大进行排序,并将排序后的学生信息打印出来。如果学生的成绩相同,则按照学号的大小进行从小到大排序。

思路:构造一个Student类,有两个属性num(学号)和score(成绩),该类实现Comparable接口,覆写compareTo(o),在该方法里,遵循先按照成绩升序排序,如果不相等再按照学号升序排序。

import java.util.*;
class Student implements Comparable{
    int num;//学号
    int score;//成绩
    public String toString(){
        return this.num+" "+this.score;
    }
    public Student(int num,int score){
        this.num=num;
        this.score=score;
    }

    public int getScore() {
        return score;
    }

    @Override
    public int compareTo(Object o) {
        int r=Integer.compare(this.score,((Student) o).getScore());
        if(r!=0){
          return r;
        }else{
            return Integer.compare(this.num,((Student) o).num);
        }
    }
}

public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            int n=sc.nextInt();
            Student[] arr=new Student[n];
            int i=0;
            while(n>0){
                n--;
                int num=sc.nextInt();
                int score=sc.nextInt();
                Student s=new Student(num,score);
                arr[i++]=s;
            }
            //对成绩排序并输出相应的
            List list=Arrays.asList(arr);//将数组转为链表
            Collections.sort(list);
            for(Student s:arr){
                System.out.println(s.toString());
            }
        }
        sc.close();
    }
}
发布了148 篇原创文章 · 获赞 32 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/smell201611010513/article/details/98763438
今日推荐