You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java课程分配学生时触发IndexOutOfBoundsException异常求助

解决Java IndexOutOfBoundsException:混淆对象ID与集合索引的问题

嘿,我一眼就看出问题所在了——你把课程/学生的ID和集合的索引下标搞混了!这是新手常犯的错误,咱们一步步理清楚:

异常根源

报错行是这一句:

listofCourses.get(idCourse).listOfStudentss.add(listOfStudents.get(studentID));

集合的get()方法需要的是从0开始的索引下标,但你传入的idCourse和studentID是用户输入的对象ID,这两个值和集合的下标没有任何必然联系。比如你的listofCourses里只有1个课程(下标是0),但用户输入的课程ID是1,调用get(1)自然就会抛出Index 1 out of bounds for length 1的异常。

修复方案

我们需要先找到匹配ID的课程和学生对象,再进行添加操作,而不是直接用ID当索引。修改后的主逻辑代码如下:

List<Admin> listOfAdmins = new ArrayList<Admin>();
List<Student> listOfStudents = new ArrayList<Student>();
List<Teacher> listOfTeachers = new ArrayList<Teacher>();
List<Subject> listofSubjects = new ArrayList<Subject>();
List<Course> listofCourses = new ArrayList<Course>();
Scanner scan222 = new Scanner(System.in);

System.out.print(" ENTER ID OF COURSE: ");
listofCourses.forEach(System.out::print);
int idCourse = scan222.nextInt();

// 先定位到目标课程对象
Course targetCourse = null;
for (Course course : listofCourses) {
    if (course.getId() == idCourse) {
        targetCourse = course;
        break;
    }
}

if (targetCourse != null) {
    System.out.print(" ENTER ID OF STUDENT: ");
    listOfStudents.forEach(System.out::print);
    int studentID = scan222.nextInt();

    // 再定位到目标学生对象
    Student targetStudent = null;
    for (Student student : listOfStudents) {
        if (student.getId() == studentID) {
            targetStudent = student;
            break;
        }
    }

    if (targetStudent != null) {
        targetCourse.listOfStudentss.add(targetStudent);
        System.out.println("Student successfully enrolled in the course!");
    } else {
        System.out.println("Oops, no student found with ID: " + studentID);
    }

    // 输出选课结果
    System.out.println("Students in the course:");
    targetCourse.listOfStudentss.forEach(System.out::println);
} else {
    System.out.println("Oops, no course found with ID: " + idCourse);
}

// 输出所有课程信息
System.out.println("All courses:");
listofCourses.forEach(System.out::println);

// 记得关闭Scanner释放资源
scan222.close();

关键修复点

  1. 直接获取目标对象:用增强for循环遍历集合,找到匹配ID的Course和Student对象,避免使用ID作为索引。
  2. 增加健壮性判断:如果找不到对应ID的课程或学生,给出友好提示,而不是直接崩溃。
  3. 资源清理:添加scan222.close()关闭Scanner,避免内存泄漏。

进阶优化建议

如果你的课程和学生数量较多,遍历集合查找的效率会很低。可以提前把ID和对象映射到HashMap中,这样查找效率会从O(n)提升到O(1):

// 提前构建ID到对象的映射表
Map<Integer, Course> courseIdMap = new HashMap<>();
for (Course course : listofCourses) {
    courseIdMap.put(course.getId(), course);
}

Map<Integer, Student> studentIdMap = new HashMap<>();
for (Student student : listOfStudents) {
    studentIdMap.put(student.getId(), student);
}

// 查找时直接通过Map获取,无需遍历
Course targetCourse = courseIdMap.get(idCourse);
Student targetStudent = studentIdMap.get(studentID);

这样代码会更简洁,性能也更好!

内容的提问来源于stack exchange,提问作者Isabay007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:25:30