4、 (学生选课)根据下面的类图,编写课程Course类和学生Student类。
Course类说明如下:
(1)addStudent方法用于添加一个选课的学生;
(2)toString方法用于返回课程的所有信息,包括课程名称和选课学生。
Student类说明如下:
(1)toString方法用于返回学生的信息。
注意:图中省略了两个类所有数据域的修改器和读取器。
编写测试类,创建一门课程对象和两个学生对象,为该课程添加两个选课学生。
样例如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
@Test
public void test() {
class Student {
private int stuNo;
private String name;
Student() {
}
Student(int stuNo, String name) {
this.stuNo = stuNo;
this.name = name;
}
@Override
public String toString() {
return "Student{" + "stuNo=" + stuNo + ", name='" + name + '\'' + '}';
}
}
class Course {
private String name;
private List<Student> stuList;
private int numberOfStudents;
Course() {
}
Course(String name) {
this.name = name;
}
Course(String name, List<Student> stuList, int numberOfStudents) {
this.name = name;
this.stuList = stuList;
this.numberOfStudents = numberOfStudents;
}
public Course addStudent(Student stu) {
if (CollectionUtil.isEmpty(stuList)) {
stuList = new ArrayList<>();
}
stuList.add(stu);
return this;
}
@Override
public String toString() {
return "Course{" + "name='" + name + '\'' + ", stuList=" + stuList + ", numberOfStudents=" + numberOfStudents
+ '}';
}
}
Scanner scanner = new Scanner(System.in);
System.out.println("请输入选课课程名称");
String courseName = scanner.nextLine();
Course course = new Course(courseName);
scanner = new Scanner(System.in);
System.out.println("请输入学生学号");
int student1No = scanner.nextInt();
scanner = new Scanner(System.in);
System.out.println("请输入学生姓名");
String student1Name = scanner.nextLine();
Student student1 = new Student(student1No, student1Name);
scanner = new Scanner(System.in);
System.out.println("请输入学生学号");
int student2No = scanner.nextInt();
scanner = new Scanner(System.in);
System.out.println("请输入学生姓名");
String student2Name = scanner.nextLine();
Student student2 = new Student(student2No, student2Name);
course.addStudent(student1);
course.addStudent(student2);
System.out.println("课程名称 "+course.name);
System.out.println("选课学生名单");
for(Student student : course.stuList){
System.out.print("学号 "+student.stuNo);
System.out.println(" 姓名"+student.name);
}
}