1. 程式人生 > >Java練習之學生選課

Java練習之學生選課

使用集合來建立一個簡單的學生選課系統。

先建立學生類和課程類,將課程資訊定義成HashSet集合。

public class Course {

	public String id;
	
	public String name;

	public Course(String id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
}

 

public class Student {

	public String name;
	
	public String id;
	
	public Set courses;

	public Student(String name, String id) {
		super();
		this.name = name;
		this.id = id;
		this.courses = new HashSet();
		
	}
}

建立ListTest類,實現課程的新增和刪除。

public class ListTest {

	public List coursesToSelect; //存放備選課程的List

	public ListTest() {
		
		this.coursesToSelect = new ArrayList();
	}
	
//新增課程
	public void testAdd()
	{
		
		coursesToSelect.add(new Course("1","資料結構"));//建立一個課程物件,並新增到課程list中
	
		coursesToSelect.add(new Course("2","計算機網路"));//建立一個課程物件,並新增到課程list中
		
		Course[] course = { new Course("3","組成原理"),new Course("4","作業系統")};
		
		coursesToSelect.addAll(Arrays.asList(course));
		
	//	coursesToSelect.set(3, new Course("4","高等數學"));

		coursesToSelect.removeAll(Arrays.asList(course));
		
	}
	public void testIterator()
	{
        Iterator it = coursesToSelect.iterator();
		
        System.out.println("通過迭代器訪問集合元素:");
		while(it.hasNext())
		{
			Course cou = (Course)it.next();
			System.out.println(cou.id+","+cou.name);
		}
		
	}
	public void testForEach()
	{
		System.out.println("通過ForEach方法訪問集合元素:");
		for(Object obj : coursesToSelect)
		{
			Course cor = (Course)obj;
			
			System.out.println(cor.id+","+cor.name);
			
		}
	}

	
	 public static void main(String[] args)
	 {
		 ListTest lt = new ListTest();
		 
		 lt.testAdd();
		// lt.testForEach();
		 lt.testIterator();
	 }
}

泛型測試:只能傳遞Course型別的資料:

public class TestGeneric {
	
	public List<Course> courses;

	public TestGeneric() {
		super();
		this.courses = new ArrayList<Course>();
	}
	
	public void testAdd()
	{
		courses.add(new Course("1","高等數學"));
		
		courses.add(new Course("2","概率論與數理統計"));
	}
	
	public void testForEach()
	{
		for(Course cor:courses)
		{
			System.out.println(cor.id+","+cor.name);
		}
	}

	public static void main(String[] args)
	{
		TestGeneric tg = new TestGeneric();
		
		tg.testAdd();
		
		tg.testForEach();
		
	}
}

泛型中可新增Course的子類ChildCourse中的資料

public class ChildCourse extends Course {
	
	public ChildCourse(String id , String name)
	{
		this.id = id;
		
		this.name = name;
	}

}

//在ListTestf的testAdd方法中,可新增ChildCourse型別的資料

courses.add(new ChildCourse("3","線性代數"));