题解 | #成绩排序#

成绩排序

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

import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[]args) {
        Scanner input = new Scanner(System.in);
        ArrayList<Student>list = new ArrayList<Student>();
        int n = input.nextInt();
        int direction = input.nextInt();
       for (int i = 0; i < n; i++) {
                String a=input.next();
            int score=input.nextInt();
            list.add(new Student(a,score ));
       }
        if (direction == 0) {
            list = Usort(list);
        } else {
            list = Dsort(list);
        }
        for (Student student : list) {
            System.out.println(student.name+" "+student.score);
        }

    }

    public static ArrayList<Student> Usort(ArrayList<Student> list) {
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if (o1.score > o2.score) {
                    return -1;
                } else if (o1.score < o2.score) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        return  list;
    }

    public static ArrayList<Student> Dsort(ArrayList<Student> list) {
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if (o1.score < o2.score) {
                    return -1;
                } else if (o1.score > o2.score) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        return  list;
    }

    public static class Student {
        private  String name;
        private  int score;

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

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

        public String getName() {
            return name;
        }

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

    }
}

全部评论

相关推荐

09-18 20:41
门头沟学院 Java
要个offer怎么这...:哈哈哈哈哈哈,我也拿了0x10000000个offer,秋招温啦啦啦,好开心
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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