题解 | #成绩排序#

成绩排序

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) {
            int num = in.nextInt();
            in.nextLine();
            int order = in.nextInt();
            in.nextLine();
            Student[] students = new Student[num];
            for (int i = 0; i < num; i++) {
                String text = in.nextLine();
                String name = text.split(" ")[0];
                int score = Integer.parseInt(text.split(" ")[1]);
                Student student = new Student(name, score);
                students[i] = student;
            }
            if (order == 1) {
                Arrays.sort(students, new Comparator<Student>() {
                    @Override
                    public int compare(Student o1, Student o2) {
                        return Integer.compare(o1.score, o2.score);
                    }
                });
            } else {
                Arrays.sort(students, new Comparator<Student>() {
                    @Override
                    public int compare(Student o1, Student o2) {
                        return Integer.compare(o2.score, o1.score);
                    }
                });
            }
            for (Student student : students) {
                System.out.println(student.name + " " + student.score);
            }
        }
    }
}

class Student {
    String name;
    int score;

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

全部评论

相关推荐

11-18 09:44
Java
小白也想要offer:简历别放洋屁,搞不还还放错了,当然你投外企除外,以上纯属个人观点
点赞 评论 收藏
分享
听说改名字就能收到offer哈:Radis写错了兄弟
点赞 评论 收藏
分享
1 3 评论
分享
牛客网
牛客企业服务