学生类:
import java.util.HashSet;
import java.util.Set;
public class Student {
public String id;
public String name;
public Set<Course> courses;
public Student(String id,String name){
this.id = id;
this.name = name;
this.courses = new HashSet();
}
}
测试类:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class SetTest {
public List<Course> coursesToSelect;
public SetTest(){
this.coursesToSelect = new ArrayList<Course>();
}
public void testAdd(){
Course c1 = new Course("1","数据结构");
coursesToSelect.add(c1);
Course c2 = new Course("2","C语言");
coursesToSelect.add(1,c2);
Course[] c = {new Course("3","离散数学"),new Course("4","汇编语言")};
coursesToSelect.addAll(Arrays.asList(c));
}
public void testForEach(){
System.out.println("有如下课程可以选:");
for(Course c : coursesToSelect){
System.out.println("课程:"+c.id+":"+c.name);
}
}
public void testForEachForSet(Student stu){
for(Course c : stu.courses){
System.out.println("选择了课程:"+c.id+":"+c.name);
}
}
public void testIteratorForSet(Student stu){
Iterator<Course> it = stu.courses.iterator();
while(it.hasNext()){
Course c = it.next();
System.out.println("选择了课程:"+c.id+":"+c.name);
}
}
public static void main(String[] args) {
SetTest st = new SetTest();
st.testAdd();
st.testForEach();
Student stu = new Student("1","小明");
System.out.println("欢迎学生:"+stu.name+"选课!");
Scanner in = new Scanner(System.in);
for(int i=0;i<3;i++){
System.out.print("输入你想选择的课程:");
String choice = in.next();
for(Course c : st.coursesToSelect){
if(c.id.equals(choice)){
stu.courses.add(c);
}
}
}
st.testIteratorForSet(stu);
}
慕仰7261054
慕粉_编程新手
相关分类