5.给定一段字符串,里面包含若干个学生上机和笔试成绩如
String str = "张三:上机成绩=90,笔试成绩=78;" +
"李四:上机成绩=68,笔试成绩=98;" +
"王五:上机成绩=48,笔试成绩=58;" +
"赵六:上机成绩=55,笔试成绩=11;" +
"jim:上机成绩=44,笔试成绩=55;" +
"tom:上机成绩=22,笔试成绩=55";
要求:
按照总分进行升序显示输出
public class Test {
public static void main(String[] args) {
String str = "张三:上机成绩=90,笔试成绩=78;" +
"李四:上机成绩=68,笔试成绩=98;" +
"王五:上机成绩=48,笔试成绩=58;" +
"赵六:上机成绩=55,笔试成绩=11;" +
"jim:上机成绩=44,笔试成绩=55;" +
"tom:上机成绩=22,笔试成绩=55";
String[] students = str.split(";");
Student[] student = new Student[students.length];
for (int i = 0; i < students.length; i++) {
// 将每个字符数组中的元素,字符串化 因为只有字符串才可以调用一些方法
String s = students[i];
//取名字
String name = s.substring(0,s.indexOf(":"));
//取上机成绩
String jc = s.substring(s.indexOf("=")+1,s.indexOf(","));
//取笔试成绩
String sc = s.substring(s.lastIndexOf("=")+1);
//这里为什么要创建一个Student对象呢? 因为只有这样才可以给类数组赋值 类数组中一个元素有这个类的所有的成员变量
Student student1 = new Student(name,Integer.valueOf(jc)+Integer.valueOf(sc));
// 如果Student这个类中的成员变量私有的化就无法调用
// student[i].name = name;
// student[i].num = Integer.valueOf(jc)+Integer.valueOf(sc);
}
//排序
Arrays.sort(student);
//打印数组一定要重写toString方法
System.out.println(Arrays.toString(student));
}
}
public class Person implements Comparable<Object> {
private int age;
private String name;
public Person() {
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
}
@Override
public int compareTo(Object o) {
Person f = (Person)o;
return this.age-f.age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}