【创建Comparator对象规定排序秩序】【Java】【P1093 】

2022/2/1 22:09:59

本文主要是介绍【创建Comparator对象规定排序秩序】【Java】【P1093 】,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package Package;

import java.io.*;
import java.util.*;

class Student{
	int ID;
	int ch;
	int ma;
	int en;
	int sum;
	public Student(int ID, int ch, int ma, int en) {
		this.ID = ID;
		this.ch = ch;
		this.ma = ma;
		this.en = en;
		this.sum=ch+ma+en;
	}
}

public class Main{

    public static void main(String[] args) throws IOException{
    	
		StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    	PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		
		in.nextToken();
    	int N = (int)in.nval;
    	
    	Student[] students=new Student[N];
		for(int i=0;i<N;i++) {
			in.nextToken();
			int ch=(int)in.nval;
			in.nextToken();
			int ma=(int)in.nval;
			in.nextToken();
			int en=(int)in.nval;
			students[i]=new Student(i+1,ch,ma,en);
		}
		
		Comparator<Student> comp = new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				if(o1.sum>o2.sum) {
					return -1;
				}else if(o1.sum==o2.sum) {
					if(o1.ch>o2.ch) {
						return -1;
					}else if(o1.ch==o2.ch) {
						if(o1.ID<o2.ID) {
							return -1;
						}else {
							return 1;
						}
					}else {
						return 1;
					}
				}
				return 1;
			}
		};
		
		Arrays.sort(students,comp);
		for(int i=0;i<5;i++) {
			out.println(students[i].ID+" "+students[i].sum);
		}
    
		out.flush();
		out.close();
    }
}


这篇关于【创建Comparator对象规定排序秩序】【Java】【P1093 】的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程