定义一个存放在包com.xhu下的包含学生学号、姓名和成绩的类Student,类中覆盖了toString()方法,toString()方法将学生信息以字符串的方式返回。然后再编写一个存放于com.test的测试类,类中对n个学生(n个Student类对象)的成绩进行升序排列并输出排序后的结果。
时间: 2023-05-21 10:04:59 浏览: 149
可以参考以下代码实现:
Student 类:
```java
package com.xhu;
public class Student {
private String id;
private String name;
private int score;
public Student(String id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
@Override
public String toString() {
return "学号:" + id + ",姓名:" + name + ",成绩:" + score;
}
public int getScore() {
return score;
}
}
```
Test 类:
```java
package com.test;
import com.xhu.Student;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Student[] students = {
new Student("001", "张三", 80),
new Student("002", "李四", 70),
new Student("003", "王五", 90)
};
Arrays.sort(students, (s1, s2) -> s1.getScore() - s2.getScore());
for (Student student : students) {
System.out.println(student);
}
}
}
```
以上代码将输出:
```
学号:002,姓名:李四,成绩:70
学号:001,姓名:张三,成绩:80
学号:003,姓名:王五,成绩:90
```
请问还有什么问题可以为您解答呢?
阅读全文