ITPub博客

首页 > 应用开发 > Java > AJPFX关于TreeSet集合的介绍

AJPFX关于TreeSet集合的介绍

Java 作者:AJPFX 时间:2019-05-21 10:39:58 0 删除 编辑

需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台。分析:1、创建键盘录入对象;
          2、创建TreeSet集合,使用匿名内部类实现Comparator接口,重写compara方法
          3、判断集合中元素的个数,向其中添加元素
          4、遍历集合

class Demo_TreeSet{
         public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入学生成绩格式,语文成绩,数学成绩,英语成绩,总成绩");
                TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>{
                       public int compara( Student s1,Student s2);
                                  int num = s2.getSum() - s1.getSum();
                                  return num == 0 ? 1 : num;
                });
               while(ts.size()<5){
                    String line = sc.nextLine();                                       
                    String[] arr = line.Split(",");
                    int chinese = Integer.paserInt(arr[1]);
                    int math = Integer.paserInt(arr[2]);
                    int  english = Integer.paserInt(arr[3]);
                    ts.add(new Student(arr[0],chinese,math,english));
                }
                for(Student : s : ts){
                      System.out.println(s);
                 }
          }
}
class Student{
    private String name;
    private int chinses;
    private int math;
    private int enlish;

    public Student() {}



    public Student(String name, int chinese, int math, int english) {
                super();
                this.name = name;
                this.chinese = chinese;
                this.math = math;
                this.english = english;
                this.sum = this.chinese + this.math + this.english;
        }
        public int getSum() {
                return sum;
        }
        
        public String toString() {
                return name + "," + chinese + "," + math + "," + english + "," + sum;
        }
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69920205/viewspace-2645037/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-05-03

  • 博文量
    65
  • 访问量
    58173