- 《java开发实战经典》第11章习题第8题 *
按照“姓名:年龄:成绩|姓名:年龄:成绩”的格式定义字符串 “张三:21:98|李四:22:89|王五:20:70”, 要求将每组值分别保存在Student对象之中,并对这些对象进行排序,
排序的原则为:按照成绩由高到低排序,如果成绩相等,则按照年龄由低到高排序
程序编写如下:
public class Student implements Comparable<Student>{
private String name;
private int age;
private int score;
public Student() {
super();
}
public Student(String name,int age,int score) {
super();
setName(name);
setAge(age);
setScore(score);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age > 0 && age < 50){
this.age = age;
}else{
System.out.println("年龄不合理");
}
}
public int getScore() {
return score;
}
public void setScore(int score) {
if(score > 0 && score < 150){
this.score = score;
}else{
System.out.println("成绩不合理");
}
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
}
@Override
public int compareTo(Student stu) {
//年龄和成绩均为int类型,可直接加减,结果按>0、 =0、<0三种返回,来判断大小。
//返回1,按升序排列;返回-1 ,按降序排列。
if( stu.getScore()-this.getScore() == 0){
return this.getAge() - stu.getAge();
}else{
return -(this.getScore()-stu.getScore());
}
}
import java.util.Arrays;
public class TestStudent {
public static void main(String[] args) {
//1、创建字符串对象,输入学生信息
String s1 = "张三:25:98|李四:22:89|王五:20:89";
//2、将字符串按|拆分成三组成为字符型数组
String[] s2 = s1.split("\\|"); //{张三:21:98,李四:22:89,王五:20:89}
Student[] s3 = new Student[s2.length]; //创建学生对象数组,申请配置内存空间为3
//3、循环将数组每个元素再次拆分后并
for(int i = 0 ; i < s2.length; i++){
String[] temp = s2[i].split(":");
//为拆分后的每个学生的一组信息加入学生数组
s3[i] =new Student(temp[0],Integer.parseInt(temp[1]),Integer.parseInt(temp[2]));
}
//4、按照成绩由高到低、年龄由小到大的排序原则进行打印排序
Arrays.sort(s3);
for(Student st :s3){
System.out.println(st);
}
}
}