Java用TreeSet集合录入学生成绩进行总成绩排序

要求:

在这里插入图片描述

1.创建学生类 并生成总成绩方法

package SetChengJi;

public class XueSheng {
String name;
int chinese;
int math;
int english;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getChinese() {
    return chinese;
}

public void setChinese(int chinese) {
    this.chinese = chinese;
}

public int getMath() {
    return math;
}

public void setMath(int math) {
    this.math = math;
}

public int getEnglish() {
    return english;
}

public void setEnglish(int english) {
    this.english = english;
}

public XueSheng(String name, int chinese, int math, int english) {
    this.name = name;
    this.chinese = chinese;
    this.math = math;
    this.english = english;
}

public XueSheng() {
    super();
}

public int getsum(){

    return  chinese+math+english;
}

}

2.因TreeSet集合不能存放重复数据,所有用Comparator方法完善功能

package SetChengJi;

import java.util.Comparator;

public class XueShengCompare implements Comparator {
@Override
public int compare(XueSheng x1, XueSheng x2) {

//主要条件:总分
int sum1 = x2.getsum() - x1.getsum();
//次要条件①:总分+语文成绩
int sum2 = sum10 ? x2.getChinese()-x1.getChinese() : sum1;
//次要条件②:总分+语文成绩+数学成绩
int sum3 = sum2
0 ? x2.getMath()-x1.getMath() : sum2;
//次要条件③:总分+语文成绩+数学成绩+英语成绩
int sum4 = sum30 ? x2.getEnglish()-x1.getEnglish() : sum3;
//次要条件④:总分+语文成绩+数学成绩+英语成绩+姓名
int sum5 = sum4
0 ? x2.getName().compareTo(x1.getName()) : sum4;

    return sum5;
}

}

3.测试类 存放数据 调动方法

package SetChengJi;

import java.util.Scanner;

import java.util.TreeSet;

public class Test {
public static void main(String[] args) {

    TreeSet<XueSheng> set = new TreeSet<XueSheng>(new XueShengCompare());

    Scanner sc = new Scanner(System.in);
    for (int i = 0; i <3 ; i++) {

        XueSheng xue = new XueSheng();

        System.out.println("请输入学生姓名");
        String name=sc.nextLine();
        System.out.println("请输入学生数学成绩");
        String math=sc.nextLine();
        System.out.println("请输入学生英语成绩");
        String english=sc.nextLine();
        System.out.println("请输入学生语文成绩");
        String chinese=sc.nextLine();

        xue.setName(name);
        xue.setChinese(Integer.parseInt(chinese));
        xue.setEnglish(Integer.parseInt(english));
        xue.setMath(Integer.parseInt(math));

        set.add(xue);


        }
    for (XueSheng xueSheng : set) {
        System.out.println("姓名:"+xueSheng.getName()+"       语文成绩"+xueSheng.getChinese()+"          数学成绩"+xueSheng.getMath()
                +"         英语成绩"+xueSheng.getEnglish()+"总分:"+xueSheng.getsum());
    }


}

}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值