设计类Student和类StudentClass。 (1) 类Student有字符串属性name、double属性grade和int属性age 有带参数的构造方法,可设置三个属性的值 有各个属性的置取方法 要实现Comparable接口 (2)类StudentClass有Set属性stuSet,使用TreeSet存放班级成员,有int属性size存入班级人数。 有createClass()方法: 使用下面三个预置数据的数组,为班级添加成员并设置班级人数。 String names[] = {"Tom","Jerry","Snoopy","Mary","Rose"}; double grades[] = {67,78.5,98,76.5,90}; int ages[] = {17,18,18,19,17}; 有output()方法:实现指定格式的班级成员信息输出 提示:可参考程序21.19。 要求编程实现类Student和类StudentClass,使给定的Test类能正常运行,并实现指定的输出内容。 public class Test { public static void main(String[] args) { StudentClass sClass = new StudentClass(); sClass.createClass(); System.out.println("Original Order:"); System.out.println(sClass.output()); } }
时间: 2023-07-15 20:11:25 浏览: 131
以下是类Student和类StudentClass的代码实现:
```
import java.util.*;
class Student implements Comparable<Student> {
private String name;
private double grade;
private int age;
public Student(String name, double grade, int age) {
this.name = name;
this.grade = grade;
this.age = age;
}
public String getName() {
return name;
}
public double getGrade() {
return grade;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setGrade(double grade) {
this.grade = grade;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student s) {
if (this.grade > s.getGrade()) {
return 1;
} else if (this.grade < s.getGrade()) {
return -1;
} else {
return 0;
}
}
@Override
public String toString() {
return "Name: " + name + " Grade: " + grade + " Age: " + age;
}
}
class StudentClass {
private Set<Student> stuSet;
private int size;
public StudentClass() {
stuSet = new TreeSet<Student>();
size = 0;
}
public void createClass() {
String names[] = {"Tom", "Jerry", "Snoopy", "Mary", "Rose"};
double grades[] = {67, 78.5, 98, 76.5, 90};
int ages[] = {17, 18, 18, 19, 17};
for (int i = 0; i < names.length; i++) {
Student stu = new Student(names[i], grades[i], ages[i]);
stuSet.add(stu);
size++;
}
}
public String output() {
StringBuilder sb = new StringBuilder();
sb.append("Class Size: " + size + "\n");
for (Student stu : stuSet) {
sb.append(stu.toString() + "\n");
}
return sb.toString();
}
}
public class Test {
public static void main(String[] args) {
StudentClass sClass = new StudentClass();
sClass.createClass();
System.out.println("Original Order:");
System.out.println(sClass.output());
}
}
```
输出结果为:
```
Original Order:
Class Size: 5
Name: Tom Grade: 67.0 Age: 17
Name: Mary Grade: 76.5 Age: 19
Name: Jerry Grade: 78.5 Age: 18
Name: Rose Grade: 90.0 Age: 17
Name: Snoopy Grade: 98.0 Age: 18
```
阅读全文