创建一个学生类,分别声明String name、int math、int chinese三个私有变量,并提供一系列的公共访问方法和一个总分类:getSum,这里就不贴出Student类了,主要看main函数。
代码如下:- import java.util.Comparator;
- import java.util.Scanner;
- import java.util.TreeSet;
- public class Demo {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- TreeSet<Student> stuSet = new TreeSet<>(
-
- new Comparator<Object>(){
- public int compare(Object o1, Object o2) {
- Student stu1 = (Student)o1;
- Student stu2 = (Student)o2;
- //比较总分:降序
- int sum = stu2.getSum() - stu1.getSum();
- //如果总分相同,排语文分,升序
- int num1 = (sum == 0 ? stu1.getChinese() - stu2.getChinese() : sum);
- //如果语文相同,排数学
- int num2 = (num1 == 0 ? stu1.getMath() - stu2.getMath() : num1);
- return num2;
- }});
- for(int i = 1 ;i <= 2 ; i++){
- System.out.println("请输入第 " + i + " 名学员信息:");
- System.out.print("姓名:");
- String name = sc.next();
- System.out.print("语文:");
- int chinese = sc.nextInt();
- System.out.print("数学");
- int math = sc.nextInt();
-
-
- //封装Student对象
- Student stu = new Student(name,chinese,math);
- //添加到集合
- stuSet.add(stu);
- }
-
- System.out.println("遍历集合:");
- System.out.println("\t姓名\t总分\t语文\t数学");
- for(Student stu : stuSet){
- System.out.println("\t" + stu.getName() + "\t" + stu.getSum() + "\t" +
- stu.getChinese() + "\t" + stu.getMath() + "\t" );
- }
- }
- }
复制代码
这种排序的方法,也可以用ArrayList来做,思路相似,ArrayList可以实现接口compareble,重写compreTo方法。 |
|