题解 | #成绩排序#用一个类包装一下,再使用比较器解决

成绩排序

https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b

import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Arrays;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int num = Integer.valueOf(in.nextLine());
        int way = Integer.valueOf(in.nextLine());
        ArrayList<student> ss = new ArrayList<>();
        student[] sss = new student[num];
        for(int i=0;i<num;i++){
            String str1 = in.nextLine();
            String[] str2 = str1.split(" ");
            String name = str2[0];
            Integer n = Integer.valueOf(str2[1]);
            student a = new student(n,name,i);
            sss[i]=a;
        } 
        if(way==0){
            Arrays.sort(sss,new Mycomp2());
            for(int i=0;i<sss.length;i++){
                System.out.println(sss[i].name+" "+sss[i].score);
            }
        }else{
            Arrays.sort(sss,new Mycomp());
            for(int i=0;i<sss.length;i++){
                System.out.println(sss[i].name+" "+ sss[i].score);
            }
        }
    }
    public static class student{
        public int score;
        public String name;
        public int number;
        public student(int s,String n,int num){
            score = s;
            name = n;
            number = num;
        }
    }
    public static class Mycomp implements Comparator<student>{
        @Override
        public int compare(student s1,student s2){
            return s1.score-s2.score == 0?s1.number-s2.number:s1.score-s2.score;
        }
    }

    public static class Mycomp2 implements Comparator<student>{
        @Override
        public int compare(student s1,student s2){
            return s2.score-s1.score == 0?s1.number-s2.number:s2.score-s1.score;
        }
    }
}

全部评论

相关推荐

07-02 13:52
门头沟学院 Java
点赞 评论 收藏
分享
lllllkin:感觉可以精简到一页简历,有些排版感觉不是必须的。 时间线越早的,你自己越熟悉的放前面。描述可以更精简些,一些问题解决感觉可以不用写具体技术栈,卖个关子,等面试官问。
点赞 评论 收藏
分享
06-11 17:39
门头沟学院 Java
小呆呆的大鼻涕:卧槽,用户彻底怒了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务