(1)设计一个Student类,要求: ①Student类有三个私有成员变量(属性): int sno表示学号 int sclass表示班级 int score表示成绩 ②编写有三个参数的构造方法以完成成员变量的初始化。 ③重写toString()方法,返回一个学生的各成员变量的信息,每个成员变量占一个制表位。 ④重写equals()方法用于规定班级相同的两个学生相等。 ⑤重写Comparable接口中的compareTo()方法,使学生类的数组可以通过调用Arrays类的sort()方法进行排序,排序要
时间: 2024-02-11 15:08:15 浏览: 84
按照成绩从高到低排序。
下面是实现以上要求的Student类的代码:
```java
public class Student implements Comparable<Student> {
private int sno; // 学号
private int sclass; // 班级
private int score; // 成绩
public Student(int sno, int sclass, int score) {
this.sno = sno;
this.sclass = sclass;
this.score = score;
}
@Override
public String toString() {
return String.format("%-10d%-10d%-10d", sno, sclass, score);
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return this.sclass == other.sclass;
}
@Override
public int compareTo(Student other) {
return other.score - this.score;
}
}
```
在这个类中,我们定义了三个私有成员变量,分别表示学号、班级和成绩。然后,我们编写了一个带有三个参数的构造方法,用于初始化这些成员变量。
接下来,我们重写了toString()方法,用于返回一个学生的各成员变量的信息,每个成员变量占一个制表位。重写equals()方法用于规定班级相同的两个学生相等。重写Comparable接口中的compareTo()方法,使学生类的数组可以通过调用Arrays类的sort()方法进行排序,排序要按照成绩从高到低排序。
这样,我们就完成了一个符合要求的Student类,可以进行学生信息的管理和排序。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)