成绩排序

题目描述

查找和排序 题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。
例示:
jack      70
peter     96
Tom       70
smith     67
从高到低  成绩
peter     96
jack      70
Tom       70
smith     67
从低到高
smith     67
Tom       70
jack      70
peter     96

输入描述

输入多行,先输入要排序的人的个数,然后分别输入他们的名字和成绩,以一个空格隔开
用户名字,字符串,非空串,长度不超过20;
成绩,整数,范围【0,100】
输入排序方式,0或1,0表示成绩从高到低方式输出名字和成绩,1表示成绩从低到高方式输出名字和成绩

输出描述

按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开

输入例子

3 0 fang 90 yang 50 ning 70

输出例子

fang 90 ning 70 yang 50

算法实现

import java.util.*;

/**
 * Declaration: All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            int t = scanner.nextInt();

            Student[] students = new Student[n];

            for (int i = 0; i < n; i++) {
                String name = scanner.next().trim();
                int score = scanner.nextInt();
                students[i] = new Student(name, score);
            }


            sort(t, students);

            StringBuilder builder = new StringBuilder();
            for (Student s : students) {
                builder.append(s.name).append(" ").append(s.score).append('\n');
            }

            System.out.print(builder.toString());
        }

        scanner.close();
    }

    private static void sort(int t, Main.Student[] students) {
        if (t == 1) {
            Arrays.sort(students, new Comparator<Student>() {
                @Override
                public int compare(Main.Student s, Main.Student t) {
                    return s.score - t.score;
                }
            });
        } else if (t == 0) {
            Arrays.sort(students, new Comparator<Student>() {
                @Override
                public int compare(Main.Student s, Main.Student t) {
                    return t.score - s.score;
                }
            });
        }
    }

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

        public Student(String name, int score) {
            this.name = name;
            this.score = score;
        }
    }
}
爱编程-编程爱好者经验分享平台

文章评论

  

版权所有 爱编程 © Copyright 2012. w2bc.com. All Rights Reserved.
闽ICP备12017094号-3