1、编写程序实现如下教学管理场景中的应用: (1) 设计学生、老师和课程类见下图, (2)老师能够开课,学生能选课 (3) 在主方法中测试见图2: l 老师创建一门课程,并添加58位学生来选择该课程。 l 统计出58位学生中男女数量及比重。
时间: 2023-06-02 11:02:36 浏览: 122
代码如下:
```java
// 学生类
class Student {
private String name;
private String gender;
public Student(String name, String gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
}
// 老师类
class Teacher {
private String name;
private List<Course> courses = new ArrayList<>();
public Teacher(String name) {
this.name = name;
}
public void addCourse(Course course) {
courses.add(course);
}
public List<Course> getCourses() {
return courses;
}
}
// 课程类
class Course {
private String name;
private List<Student> students = new ArrayList<>();
public Course(String name) {
this.name = name;
}
public void addStudent(Student student) {
students.add(student);
}
public List<Student> getStudents() {
return students;
}
public int getMaleCount() {
int count = 0;
for (Student student : students) {
if (student.getGender().equals("male")) {
count++;
}
}
return count;
}
public int getFemaleCount() {
int count = 0;
for (Student student : students) {
if (student.getGender().equals("female")) {
count++;
}
}
return count;
}
public double getMaleProportion() {
int maleCount = getMaleCount();
int totalCount = students.size();
return (double) maleCount / totalCount;
}
public double getFemaleProportion() {
int femaleCount = getFemaleCount();
int totalCount = students.size();
return (double) femaleCount / totalCount;
}
}
public class Main {
public static void main(String[] args) {
Teacher teacher = new Teacher("张三");
Course course = new Course("Java基础");
teacher.addCourse(course);
for (int i = 1; i <= 58; i++) {
String gender = i % 2 == 0 ? "male" : "female";
Student student = new Student("学生" + i, gender);
course.addStudent(student);
}
int maleCount = course.getMaleCount();
int femaleCount = course.getFemaleCount();
double maleProportion = course.getMaleProportion();
double femaleProportion = course.getFemaleProportion();
System.out.println("男生人数:" + maleCount);
System.out.println("女生人数:" + femaleCount);
System.out.println("男生比例:" + maleProportion);
System.out.println("女生比例:" + femaleProportion);
}
}
```
输出结果为:
```
男生人数:29
女生人数:29
男生比例:0.5
女生比例:0.5
```
阅读全文