集合练习:成绩排序(JAVA)

用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
要求:按照总分从高到低出现

学生成绩类

public class StudentScore{
	public static void main(String[] args){
		private String name;
		private int cscore;//语文成绩;
		private int mscore;//数学成绩;
		
		public class StudentScore(){}
		public class StudentScore(String name,int cscore, int mscore){
			this.name = name;
			this.cscore = CScore;
			this.mscore = MScore
		
		}
		public String getName(){
			return name;
		}
		public void setName(String name){
			this.name = name;
		}
		public int getCscore(){
			return cscore;
		}
		public void setCscore(int mscore){
			this.cscore = cscore;
		}
		public int getMscore(){
			return mscore;
		}
		public void setMscore(int mscore){
			this.mscore = mscore;
		}
		public int getSum(){
			return this.cscore + this.mscore;
	}

测试类

public class Demo{
	public static void main(String[] args){
		TreeSet<StudentScore> ts = new TreeSet<StudentScore>(new Comparator<StudentScore>){
			@Override
			public int compare(Student s1,Student s2){
				int num = s1.getSum() - s2.getSum();
				//次要条件 
				//当总分相同时比较语文分数
				int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num; 
				//当总分相同+语文分数相同:比较姓名是否相同
				int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2; 
				return num3;
			}
		}
		//创建学生对象 
		StudentScore s1 = new Student("a", 90, 90); 
		StudentScore s2 = new Student("b", 92, 90); 
		StudentScore s3 = new Student("c", 93, 90); 
		StudentScore s4 = new Student("d", 98, 90); 
		StudentScore s5 = new Student("f", 81, 90); 
		StudentScore s6 = new Student("g", 77, 90); 
		
		for (StudentScore s : ts) { 
			System.out.println(s.getName() + "," + s.getCscore() + "," + s.getMscore() + "," + s.getSum()); 
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值