IT小白啊
2019-02-01 17:40
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 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);
/*courseToSelect.add(cr1);
Course temp0=(Course) courseToSelect.get(2);
System.out.println("添加了一个课程:"+temp.id+":"+temp.name);*/
//以下方法会抛出数组下标越界异常
//Course cr3=new Course("3","xxx");
//courseToselect.add(4, cr3);
Course[] course= {new Course("3","离散数学"),new Course("4","汇编语音")};
coursesToSelect.addAll(Arrays.asList(course));
Course temp3=(Course)coursesToSelect.get(3);
coursesToSelect.get(4);
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);
}
/**
* 通过for each 方法访问集合元素
* @param args
*/
public void testForEach(){
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对象,用来接收从键盘输入的课程ID
@SuppressWarnings("resource")
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);
student.courses.add(cr);
}
}
}
st.testForEachForSet(student);
}
public void testForEachForSet(Student student) {
//打印输出 学生所选的课程
for(Course cr:student.courses) {
System.out.println("您选择了课程:"+cr.id+":"+cr.name);
}
}
}
问题:数组下标越界
testAdd() 方法中
Course temp3=(Course)coursesToSelect.get(3); coursesToSelect.get(4);
应该改成
Course temp3=(Course)coursesToSelect.get(); coursesToSelect.get();
Java入门第三季
409792 学习 · 4340 问题
相似问题