qq_晋阳乐_0
2018-11-21 10:59
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> coursesToSelect; public SetTest(){ coursesToSelect = new ArrayList<Course>(); } /** * 添加备选课程 */ public void testAdd(){ //创建课程对象,并通过调用add方法添加到备选课程List Course course01 = new Course("002","c语言"); coursesToSelect.add(course01); //对象存入集合时都变成Object类型,取出时也是object需要转换类型 Course temp = (Course) coursesToSelect.get(0); System.out.println("添加了课程:" + temp.id + ":" +temp.name); Course course02 = new Course("001","高等数学"); coursesToSelect.add(0,course02); Course temp01 = (Course) coursesToSelect.get(0); Course temp03 = (Course) coursesToSelect.get(0); Course[] courses = {new Course("003","近代诗"),new Course("004","计算机导论")}; coursesToSelect.addAll(Arrays.asList(courses)); Course temp02 = (Course) coursesToSelect.get(2); } /** * 通过for each方法访问集合元素 * * @param */ public void testForEachForSet(Student student){ // 打印输出,学生所选的课程! System.out.println("共选择了:" + student.courses.size() + "门课程!"); for (Course cr : student.courses) { System.out.println("选择了课程:" + cr.id + ":" + cr.name); } } public static void main(String[] args) { 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 testForEach() { System.out.println("有如下课程待选(通过for each访问):"); for (Object obj : coursesToSelect) { Course cr = (Course) obj; System.out.println("课程:" + cr.id + ":" + cr.name); } } }
提示选择了0门课程
这页ADD好像没什么问题 是不是其他类设置出了问题
编号问题
会不会是你在定义coursesToSelect变量时已经定义为Course泛型变量了,后面不需要转换类型了,试试
Java入门第三季
409792 学习 · 4340 问题
相似问题