java开发实战经典(第二版)P368 11-8

11.8   按照”姓名:年龄:成绩|姓名:年龄:成绩“的格式定义字符串”张三:21:98|李四:22:89|王五:20:70“,要求将每组值分别保存在Student对象之中,并对这些对象进行排序,排序的原则为:按照成绩由高到低排序,如果成绩相等,则按照年龄由低到高排序。

package book;
import java.util.Arrays;

public class JiOu {
	/**
	 * 要求可以根据每个学生的成绩进行由高到低的排序
	 * 如果成绩相等
	 * 则按照年龄由低到高排序
	 * 数据的样式如下
	 * 张三:19:90|李四:20:90|王五:20:80|赵六:21:100
	 */
	public static void main(String[] args) {
		String a="A";
		String b="B";
		mb_operate(a,b);
		System.out.println(a+"."+b);
 
		// TODO Auto-generated method stub
		String content = "张三:19:90#李四:20:90#王五:20:80#赵六:21:100";
		String[] ss = content.split("#");
		Student[] stus = new Student[ss.length];
		for (int i = 0; i < ss.length; i++) {
			String[] temp = ss[i].split(":");
			stus[i] = new Student(temp[0],Integer.valueOf(temp[1]), Integer.valueOf(temp[2]));
		}
		
		//排序
		Arrays.sort(stus);
		for (Student student : stus) {
			System.out.println(student);
		}
	}
	public static void mb_operate(String x,String y)
	{
		x.concat(y);
		y=x;
	}
 
}
 
class Student implements Comparable<Student>{
	private String name;
	private int age;
	private int score;
	
	public Student() {
		
	}
	
	public Student(String name, int age, int score) {
		this.name = name;
		this.age = age;
		this.score = score;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getAge() {
		return age;
	}
 
	public void setAge(int age) {
		this.age = age;
	}
 
	public int getScore() {
		return score;
	}
 
	public void setScore(int score) {
		this.score = score;
	}
 
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
	}
 
	@Override
	public int compareTo(Student o) {
		if(this.getScore() > o.getScore()){
			return 1;
		}else if(this.getScore() < o.getScore()){
			return -1;
		}else{
			if(this.getAge() > o.getAge()){
				return 1;
			}else if(this.getAge() < o.getAge()){
				return -1;
			}
			return 0;
		}
	}
}

运行结果:

A.B
Student [name=王五, age=20, score=80]
Student [name=张三, age=19, score=90]
Student [name=李四, age=20, score=90]
Student [name=赵六, age=21, score=100]

原文地址:https://blog.csdn.net/qq_16909139/article/details/76982434

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值