為什么我無(wú)法加入到已選課程中,courses中沒有添加到課程
package com.imooc.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SetTest {
public List<Course> courseToSelect;
public SetTest(){
courseToSelect=new ArrayList<Course>();
}
public void testAdd(){
// 創(chuàng)建一個(gè)課程對(duì)象,并通過調(diào)用add方法,添加調(diào)用add方法,添加到備選課程;List中
Course cr1=new Course("1.","數(shù)據(jù)結(jié)構(gòu)");?
courseToSelect.add(cr1);
Course temp=(Course) courseToSelect.get(0);
// System.out.println(temp.id+temp.name);
Course cr2=new Course("2.","C語(yǔ)言");
courseToSelect.add(1,cr2);
Course temp2=(Course) courseToSelect.get(1);
// System.out.println(temp2.id+temp2.name);
Course[] cr3={new Course("3.","離散數(shù)學(xué)"),new Course("4.","匯編語(yǔ)言")};
courseToSelect.addAll(Arrays.asList(cr3));
Course temp3=(Course) courseToSelect.get(2);
Course temp4=(Course) courseToSelect.get(3);
// System.out.println(temp3.id+temp3.name+temp4.id+temp4.name);
Course[] cr4={new Course("5.","算法"),new Course("6.","大學(xué)英語(yǔ)")};
courseToSelect.addAll(0,Arrays.asList(cr4));
Course temp5=(Course) courseToSelect.get(4);
Course temp6=(Course) courseToSelect.get(5);
// System.out.println(temp5.id+temp5.name+temp6.id+temp6.name);
}
public void foreach(){
System.out.println("foreach");
for(Course cr:courseToSelect){
System.out.println(cr.id+cr.name);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SetTest st=new SetTest();
st.testAdd();
st.foreach();
Student student=new Student("1","小米");
System.out.println("歡迎"+student.name+"選課");
Scanner console=new Scanner(System.in);
for(int i=0;i<3;i++){
System.out.println("輸入課程ID");
String courseId=console.next();
for(Course cr:st.courseToSelect){
if(cr.id.equals(courseId)){
student.courses.add(cr);
}
}
}
st.tesx(student);
System.out.println(student.courses.size());
}
public void tesx(Student student){
for(Course cr:student.courses){
System.out.println(cr.id+cr.name);
}
}
}
//學(xué)生類
package com.imooc.collection;
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<Course>();
? ? }
}
//Course 類
package com.imooc.collection;
public class Course {
?
? ? public String id;
? ? ?
? ? public String name;
? ? ?
? ? public Course(String id, String name) {
? ? ? ? this.id = id ;
? ? ? ? ?
? ? ? ? this.name = name;
? ? }
? ? ?
? ? public Course() {
? ? ? ? ?
? ? }
}
2016-09-24
testAdd()里面添加的Course的id都是"1.", "2."....所以你在輸入課程ID的時(shí)候也要輸入數(shù)字加"."的方式才能使cr.id.equals(courseId)