Java語言編寫Student(姓名:年齡:成績)資訊排序,重寫compareTo()方法
阿新 • • 發佈:2018-11-22
- 《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); } } }