题解 | #成绩排序#

成绩排序

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

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int num = sc.nextInt();

        ArrayList<Student> list = new ArrayList<>();

        int type = sc.nextInt();

        for (int i = 0; i < num; i++) {
            String name = sc.next();
            int score = sc.nextInt();
            list.add(new Student(name, score));
        }

        Comparator<Student> comparator = type == 1 ?
        new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((Student) o1).score - ((Student) o2).score;
            }
        } : new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((Student) o2).score - ((Student) o1).score;
            }
        };

        list.sort(comparator);

        for (Student student : list) {
            System.out.println(student.name + " " + student.score);
        }
    }
}

class Student {
    String name;
    Integer score;

    public Student() {
    }

    public Student(String name, Integer score) {
        this.name = name;
        this.score = score;
    }


}

成员变量最好还是私有化

全部评论

相关推荐

点赞 评论 收藏
分享
MomonKa:我拿Java简历投了pdd前端也给我简历过筛了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务