用Java编写Student类,有如下功能:1、学号以各专业、年纪分类自动编号。2、实现以多种条件进行查找,例如,只比较姓名,查找姓“李”的人,查找某年出生的人,查找某省某市的人等。3、增加多门成绩变量;按照专业分别统计不同班级的学生成绩。
时间: 2024-10-25 21:14:54 浏览: 7
java代码-【3】定义一个学生类,使用LinkedList对学生类进行管理,执行添加操作,并打印数据。 运行效果图为: 任务: 1.定义一个学生类Student (1)属性为:学号stuId(int),姓名name(String),成绩score(float) (2)方法为:构造方法,getter和setter方法,toString方法 2.定义三个Student类的对象,添加到LinkedList中 3.显示LinkedList中元素的内容
在Java中,我们可以创建一个名为`Student`的类来实现这些需求。首先,我们需要包含一些基本属性如姓名、年龄、出生日期、省份、城市以及多门成绩。为了实现自动生成学号,我们可以在类中添加一个静态变量和构造函数来处理:
```java
public class Student {
private static int autoId = 0;
private String name;
private String major;
private int age;
private Date birthDate;
private String province;
private String city;
private Map<String, List<Double>> scoresBySubject; // 存储各科成绩
public Student(String name, String major, int age, String birthDateStr, String province, String city) {
this.name = name;
this.major = major;
this.age = age;
this.birthDate = new SimpleDateFormat("yyyy-MM-dd").parse(birthDateStr);
this.province = province;
this.city = city;
this.scoresBySubject = new HashMap<>();
this.autoId = generateAutoId();
}
private int generateAutoId() {
return autoId++;
}
// 查找方法,如按姓名、年龄、出生日期和地点查找
public boolean searchByName(String lastName) {
return name.contains(lastName);
}
public boolean searchByAge(int targetAge) {
return age == targetAge;
}
public boolean searchByBirthYear(int targetYear) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(birthDate);
return calendar.get(Calendar.YEAR) == targetYear;
}
public boolean searchByLocation(String targetProvince, String targetCity) {
return province.equals(targetProvince) && city.equals(targetCity);
}
// 添加成绩并统计
public void addScore(String subject, double score) {
if (!scoresBySubject.containsKey(subject)) {
scoresBySubject.put(subject, new ArrayList<>());
}
scoresBySubject.get(subject).add(score);
}
public Map<String, Double> getAverageScoresByMajor() {
return scoresBySubject.entrySet().stream()
.filter(entry -> entry.getKey().startsWith(major))
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().stream().average().orElse(0)));
}
// ...其他相关getter和setter方法
}
```
阅读全文