题解 | #成绩排序#

成绩排序

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

自定义类可以实现Comparable接口

import java.util.ArrayList;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Student.flag = in.nextInt();
        ArrayList<Student> list = new ArrayList<>();
        // 注意 hasNext 和 hasNextLine 的区别
        while (n-- > 0) { // 注意 while 处理多个 case
            list.add(new Student(in.next(), in.nextInt()));
        }
        list.stream().sorted().forEach(System.out::println);
    }
}

class Student implements Comparable<Student> {
    String name;
    int score;
    static int flag;

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

    @Override
    public String toString() {
        return String.format("%s %d", this.name, this.score);
    }

    @Override
    public int compareTo(Student o) {
        return flag == 1 ? this.score - o.score : o.score - this.score;
    }
}

全部评论

相关推荐

Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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