liu4444
2016-01-08 15:55
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SetTest {
public List<Course> coursesToSelect;
public SetTest(){
coursesToSelect=new ArrayList<Course>();
}
public void testAdd(){
Course cr1 = new Course("1","数据结构");
coursesToSelect.add(cr1);
Course temp= (Course) coursesToSelect.get(0);
//System.out.println("添加了课程:" + temp.id + ":" + temp.name);
Course cr2= new Course("2","C语言");
coursesToSelect.add(0,cr2);
Course temp2= (Course) coursesToSelect.get(0);
//System.out.println("添加了课程:" + temp2.id + ":" + temp2.name);
//coursesToSelect.add(cr1);
//Course temp0= (Course) coursesToSelect.get(2);
//System.out.println("添加了课程:" + temp0.id + ":" + temp0.name);
Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")};
coursesToSelect.addAll(Arrays.asList(course));
Course temp3 = (Course)coursesToSelect.get(3);
Course temp4 = (Course)coursesToSelect.get(4);
//System.out.println("添加了两门课程:" + temp3.id + ":" + temp3.name+";"+ temp4.id + ":" + temp4.name);
Course[]course2 = {new Course("5","高等数学"),new Course("6","大学英语")};
coursesToSelect.addAll(2,Arrays.asList(course2));
Course temp5 = (Course)coursesToSelect.get(2);
Course temp6 = (Course)coursesToSelect.get(3);
//System.out.println("添加了两门课程:" + temp5.id + ":" + temp5.name+";"+ temp6.id + ":" + temp6.name);
}
private void testForEach() {
// TODO Auto-generated method stub
System.out.println("有如下课程待选(通过for each访问):");
for(Object obj:coursesToSelect){
Course cr = (Course)obj;
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.testForEach();
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.coursesToSelect){
if(cr.id.equals(courseId)){
student.courses.add(cr);
}
}
}
st.testForEachForSet(student);
}
public void testForEachForSet(Student student){
for(Course cr:student.courses){
System.out.println("选择了课程:"+cr.id+":"+cr.name);
}
}
}
Course temp3 = (Course)coursesToSelect.get(3);//你的代码中获取到的是地址为3的信息,是("4","汇编语言")
Course temp4 = (Course)coursesToSelect.get(4);//地址是4的信息,地址4现在还木有信息啊,这里应该是3,上面应该是2
因为地址从0开始放,开始地址0是数据结构,结果又把c语言放在0位置,那么数据结构就在1位置,你又放了两个(离散数学、汇编语言),地址在2,3的位置上,然后又放2门课(高等数学、大学英语)在2的位置,那么地址位置又变了,现在0放c语言,1放数据结构,2放高等数学,3放大学英语,4放离散数学,5放汇编语言。
Java入门第三季
409792 学习 · 4340 问题
相似问题