案例之键盘录入学生信息按照总分排序

package MONA.demo06_treeset;

import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

public class Demo04 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        TreeSet<Student2> ss = new TreeSet<>( new Comparator<Student2>() {
            @Override
            public int compare(Student2 o1, Student2 o2) {
                //按照总分进行排序
                int i1 = o1.getSum()-o2.getSum();//按成绩升序排名
                //总分相同,那么按语文成绩升序排序
                int i2 = (i1 == 0) ? o1.getChinese() - o2.getChinese() : i1;
                //语文成和总分都相同
                // 按数学成绩进行排序
                int i3 = (i2 == 0) ? o1.getMath() - o2.getMath() : i2;
                return i3;
            }
        });
        for (int i = 0; i < 2; i++) {
            System.out.println("请输入第" + (i+1)+"个学生的信息");
            System.out.println("请输入姓名");
            String name = sc.next();
            System.out.println("请输入语文成绩");
            int chinese = sc.nextInt();
            System.out.println("请输入数学成绩");
            int math = sc.nextInt();
            System.out.println("请输入英语成绩");
            int english = sc.nextInt();

            //封装对象
            Student2 s = new Student2(name, chinese, math, english);
            ss.add(s);
        }
        System.out.println(ss);
    }
}
class Student2{
    private String name;
    private int chinese;//语文成绩
    private int math;//数学成绩
    private int english;//英语成绩

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

    //提供获取总分的方法
    public int getSum(){
        return chinese + math + 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;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "name='" + name + '\'' +
                ", chinese=" + chinese +
                ", math=" + math +
                ", english=" + english +
                '}';
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值