定义一个存放在包com.xhu下的包含学生学号、姓名和成绩的类Student,类中覆盖了toString()方法,toString()方法将学生信息以字符串的方式返回。然后再编写一个存放于com.test的测试类,类中对n个学生(n个Student类对象)的成绩进行升序排列并输出排序后的结果。
时间: 2023-05-21 11:05:11 浏览: 72
以下是定义类Student和测试类的完整代码:
Student类:
```
package com.xhu;
public class Student {
private String id;
private String name;
private float score;
public Student(String id, String name, float score) {
this.id = id;
this.name = name;
this.score = score;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", score=" + score +
'}';
}
}
```
测试类:
```
package com.test;
import com.xhu.Student;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
// 创建n个学生
int n = 5;
Student[] students = new Student[n];
students[0] = new Student("1001", "张三", 85);
students[1] = new Student("1002", "李四", 90);
students[2] = new Student("1003", "王五", 70);
students[3] = new Student("1004", "赵六", 80);
students[4] = new Student("1005", "陈七", 95);
// 对学生的成绩进行升序排序
Arrays.sort(students, (o1, o2) -> Float.compare(o1.getScore(), o2.getScore()));
// 输出排序后的结果
System.out.println("排序后的结果:");
for (Student student : students) {
System.out.println(student);
}
}
}
```
执行该测试类的main方法会输出如下结果:
```
排序后的结果:
Student{id='1003', name='王五', score=70.0}
Student{id='1004', name='赵六', score=80.0}
Student{id='1001', name='张三', score=85.0}
Student{id='1002', name='李四', score=90.0}
Student{id='1005', name='陈七', score=95.0}
```
阅读全文