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