问答详情
源自:4-6 学生选课—课程查询

好心累,真的是。。打完了一样也有错= = 求大神

package 课程选择;


import java.util.List;


public class ListTest {


public List coursesToSelect;

public ListTest()

{

this.coursesToSelect=new ArrayList();

}

/*用于往coursesToSelect中添加备选课程*/

   

public void testAdd(){

//创建一个课程对象,并通过调用add方法,添加到备选课程List中

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);

/*以下方法会抛出数组下标越界异常

Course cr3=new Course("3","List");

coursesToSelect.add(4,cr3);*/

Course[] course={new Course("3","离散数学"),new Course("4","汇编语言")};

coursesToSelect.add(Arrays.asList(course));

Course temp3=(Course)coursesToSelect.get(2);

Course temp4=(Course)coursesToSelect.get(3);

System.out.println("添加了课程"+temp3.id+":"+temp3.name);

System.out.println("添加了课程"+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);

System.out.println("添加了课程"+temp6.id+":"+temp6.name);

}

//取得List 中的元素方法

public void testGet(){

int size=coursesToSelect.size();

System.out.println("有如下课程可以选择:");

for(int i=0;i<size;i++)

{

Course cr=(Course)coursesToSelect.get(i);

System.out.println("课程:"+cr.id+":"+cr.name);

}

}

public static void main(String args[])

{

ListTest It=new ListTest();

It.testAdd();

It.testGet();

}

}


提问者:慕无忌6386368 2016-04-20 20:15

个回答

  • 慕工程2293914
    2016-04-20 22:03:45

    public class Course {


    public String id;


    public String name;


    public Course(String id, String name) {

    this.id = id;


    this.name = name;

    }


  • 慕工程2293914
    2016-04-20 22:02:41

    先导入import java.util.ArrayList;

    然后你在 package 课程选择 包下新建一个Course类

    然后就ok啦~~


  • rich617
    2016-04-20 21:48:11

    太粗心了吧~报错的地方是在添加3,4的地方,应该是addAll而不是add

    Course[] courses={new Course("3","离散数学"),new Course("4","汇编语言")};

    coursesToSelect.addAll(Arrays.asList(courses));