成绩排序

来源:互联网 发布:营销数据分析工具 编辑:程序博客网 时间:2024/06/10 06:24

package oj.test;

import java.util.*;
public class Demo5 {

 /**
  * @成绩排序
  * 查找和排序
  * 题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩 都按先录入排列在前的规则处理。
  */
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  
  String num = sc.nextLine();
  String flag = sc.nextLine();
  Integer nu = Integer.parseInt(num);
  
  TreeSet<Student1> ts = new TreeSet<Student1>();
  TreeSet<Student2> ts2 = new TreeSet<Student2>();
  
  while((nu--)>0){
   String input = sc.nextLine();
   String[] s = input.split(" ");
   String n = s[0];
   Integer a = Integer.parseInt(s[1]);
   Student1 stu = new Student1(n,a);
   ts.add(stu);
   
   Student2 stu2 = new Student2(n,a);
   ts2.add(stu2);
  }
  
  
  
  if(flag.equals("1"))
   up(nu,ts);
  else if(flag.equals("0"))
   down(nu,ts2);

  
  
 }
 
 

 private static void down(Integer nu, TreeSet<Student2> ts2) {
  Iterator<Student2> it = ts2.iterator();
  while(it.hasNext()){
   Student2 stu = it.next();
   sop(stu.getName()+ " " +stu.getScore());
  }
 }

 

 private static void up(Integer nu, TreeSet<Student1> ts) {
  Iterator<Student1> it = ts.iterator();
  while(it.hasNext()){
   Student1 stu = it.next();
   sop(stu.getName()+ " " +stu.getScore());
  }
 }

 

 private static void sop(Object obj) {
  System.out.println(obj);
 }

}
//升序
class Student1 implements Comparable{
 private String name;
 private int score;

 @Override
 public int compareTo(Object o) {
  Student1 s = (Student1) o;
  if( this.score>s.score)
   return 1;
  else if(this.score==s.score){
   if(this.name.compareTo(s.name)>0)
    return 1;
   else if(this.name.compareTo(s.name)<0)
    return -1;
   else
    return 0;
  }
  else
   return -1;
 }
 public Student1(String name,int score){
  this.name = name;
  this.score = score;
 }
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getScore() {
  return score;
 }
 public void setScore(int score) {
  this.score = score;
 }
 
}

//降序
class Student2 implements Comparable{
 private String name;
 private int score;

 @Override
 public int compareTo(Object o) {
  Student2 s = (Student2) o;
  if( this.score>s.score)
   return -1;
  else if(this.score==s.score){
   if(this.name.compareTo(s.name)>0)
    return -1;
   else if(this.name.compareTo(s.name)<0)
    return 1;
   else
    return 0;
  }
  else
   return 1;
 }
 public Student2(String name,int score){
  this.name = name;
  this.score = score;
 }
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getScore() {
  return score;
 }
 public void setScore(int score) {
  this.score = score;
 }

}

0 0