package com.imooc.collection;
import java.util.HashSet;
import java.util.Set;
/**
* 学生类
* @author 鹏
*
*/
public class Student {
public String id;
public String name;
//定义一个存放选择的课程的集合
public Set<String> Courses;
//定义一个构造器来传入id,name和Course
public Student(String id,String name){
this.id=id;
this.name=name;
this.Courses=new HashSet<String>();//将选择的课程集合实例化
}
}
2.
package com.imooc.collection;
/**
* 课程类
* @author 鹏
*
*/
public class Course {
//定义两哥公用的Course的属性
public String id;
public String name;
//创建一个构造器,令我们输入的id+name传入Course里面
public Course(String id,String name){
this.id=id;
this.name=name;
}
public Course(){
}
}
3.
package com.imooc.collection;
public class ChildCourse extends Course {
}
4.
package com.imooc.collection;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SetText {
public List<Course> coursesToselect;
public SetText(){
coursesToselect =new ArrayList<Course>();
}
public void add(){
Course cr1 = new Course("1","程序设计基础");
coursesToselect.add(cr1);
Course cr2 = new Course("2","计算机网络");
coursesToselect.add(cr2);
Course cr3 = new Course("3","数据结构");
coursesToselect.add(cr3);
Course cr4 = new Course("4","高数");
coursesToselect.add(cr4);
Course cr5 = new Course("5","线代");
coursesToselect.add(cr5);
Course cr6 = new Course("6","概率论与数理统计");
coursesToselect.add(cr6);
Course cr7 = new Course("7","大学英语");
coursesToselect.add(cr7);
Course cr8 = new Course("8","马原");
coursesToselect.add(cr8);
}
public void ForEach(){
for (Course course : coursesToselect) {
System.out.println("课程:"+course.id+":"+course.name);
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Student student = new Student("1","小明");
System.out.println("欢迎"+student.name+"同学来选课");
System.out.println("\n可以被选择的课程有:");
SetText H = new SetText();
H.add();
H.ForEach();
Scanner in=new Scanner(System.in);
for(int i = 0;i<3;i++){
System.out.println("请输入课程的ID:");
String courseid = in.next();
for (Course cr : H.coursesToselect) {
if(cr.id.equals(courseid)){
student.Courses.add(cr);
}
}
}
}
public void TextForEach(Student student){
for (Course cr : student.Courses) {
System.out.println("选择了课程:"+cr.id+":"+cr.name);
}
}
}
应该把Student 类里面的
//定义一个存放选择的课程的集合
public Set<String> Courses;
改为 public Set<Course> Courses;
注意:你放的泛型应该为Course 类型