zoukankan      html  css  js  c++  java
  • Comparator 排序 ArrayList 实操练习

    package ltb6w;


    import java.util.Scanner;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Collections;


    class GradeStatistic {

    Scanner sc=new Scanner(System.in);

    private String entername=null ;

    private int inputscore = 0;

    private List<Mark> al=new ArrayList<Mark>();

    private Comparator<Mark> ScoresRanking;
    private Comparator<Mark> SortByName;


    public GradeStatistic() {


    }


    class Mark {

    private int score;
    private String name;

    public Mark(String n,int i) {


    score=i;
    name=n;

    }

    public int getScore() {

    return score;
    }

    public String getName() {

    return name;

    }


    }



    public void enter() throws Exception {


    while(true) {


    entername= sc.next();

    if(entername.equals("over")) {
    break;
    }

    inputscore=sc.nextInt();


    al.add(new Mark(entername,inputscore));


    System.out.print("姓名:"+this.entername+",分数:"+inputscore+" ");



    }


    }

    public void getScoresRanking() {

    this.ScoresRanking=new ScoresRanking(); //连接上对象

    try {
    Collections.sort(al,ScoresRanking );
    }catch(Exception e) {
    e.getMessage();
    }

    for(int i=0;i<al.size();i++) {

    System.out.println("分数排序-->"+"姓名:"+al.get(i).getName()+"分数:"+al.get(i).getScore());

    }
    }


    public void getSortByName() {

    this.SortByName=new SortByName();//连接上对象

    try {
    Collections.sort(al,SortByName );
    }catch(Exception e) {
    e.getMessage();
    }

    for(int j=0;j<al.size();j++) {

    System.out.println("姓名排序"+"姓名:"+al.get(j).getName()+"分数:"+al.get(j).getScore());

    }
    }

    public class ScoresRanking implements Comparator<Mark>{

    //分数排序

    public int compare(Mark arg0, Mark arg1) {

    return (arg0.getScore()<arg1.getScore()?-1:(arg0.getScore()==arg1.getScore()?0:1));

    }

    }


    public class SortByName implements Comparator<Mark> {

    //姓名排序

    public int compare(Mark m1,Mark m2) {

    return (m1.getName().compareTo(m2.getName()));
    }
    }



    public static void main(String[] args) {

    GradeStatistic gs= new GradeStatistic();

    System.out.print("输入姓名和分数:"+" ");

    try {
    gs.enter();
    } catch (Exception e) {

    e.printStackTrace();
    }

    gs.getScoresRanking();//分数排序
    gs.getSortByName();//姓名排序

    }



    }

     

  • 相关阅读:
    SpringBoot自动配置原理(七)
    SpringBoot 集成Shiro
    Shiro配置跳过权限验证
    rsync+ssh同步备份文件
    okhttp3设置代理(http/https)
    Spring RestTemplete支持Https安全请求
    电商课题V:分布式锁
    电商课题:对付秒杀器等恶意访问行为的简单梳理
    电商课题:客户端的IP地址伪造、CDN、反向代理、获取的那些事儿
    电商课题I:集群环境下业务限流
  • 原文地址:https://www.cnblogs.com/ltb6w/p/7965938.html
Copyright © 2011-2022 走看看