为什么我得到一个数组IndexOutOfBounds错误?

时间:2017-08-29 09:51:56

标签: java arrays

我有一本java书,正在做一些关于阵列的练习。任何人都可以帮助我理解为什么这是出界的? 练习是创建3个课程:一个CollegeCourse;学生和InputGrades与主要方法。当我运行它时,它会很好,直到它显示我的数组超出范围。当我即将进入第三个学生的第二门课程时,它会崩溃。

public static void main(String[] args) {
    String info = null;
    int infoInt = 0;
    char infoChar = 0;

    Scanner input = new Scanner(System.in);

    CollegeCourse[] courses = new CollegeCourse[2];
    for(int i = 0; i < courses.length; i++) {
        courses[i] = new CollegeCourse();
    }

    Student[] students = new Student[3];
    for(int i = 0; i < students.length; i++) {
        students[i] = new Student();
    }
    System.out.println("Welcome to Java Programming.\n   Professor, enter your students' info below.");
    for(int i = 0; i < students.length; i++) {
        System.out.print("\nEnter student ID >>> ");
        infoInt = input.nextInt();
        input.nextLine();
        students[i].setStudentID(infoInt);

        for(int j = 0; j < courses.length; j++) {
            System.out.print("Enter course ID >>> ");
            info = input.nextLine();
            courses[j].setCourseID(info);

            System.out.print("Enter credit hours >>> ");
            infoInt = input.nextInt();
            input.nextLine();
            courses[j].setCreditHours(infoInt);

            System.out.print("Enter letter grade >>> ");
            info = input.nextLine();
            info = info.toUpperCase();
            info.toCharArray();
            infoChar = info.charAt(0);
            courses[i].setLetterGrade(infoChar);
        }
    }
}

我的输出是:

Welcome to Java Programming.
  Professor, enter your students' info below.

Enter student ID >>> 1468
Enter course ID >>> cis 210
Enter credit hours >>> 3
Enter letter grade >>> b
Enter course ID >>> smm 310
Enter credit hours >>> 5
Enter letter grade >>> a

Enter student ID >>> 1449
Enter course ID >>> cis 210
Enter credit hours >>> 5
Enter letter grade >>> a
Enter course ID >>> smm 310
Enter credit hours >>> 5
Enter letter grade >>> a

Enter student ID >>> 1986
Enter course ID >>> cis 210
Enter credit hours >>> 2
Enter letter grade >>> c
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
   at Chapter08Arrays.InputGrades.main(InputGrades.java:48)

2 个答案:

答案 0 :(得分:3)

您的上一行显示

courses[i].setLetterGrade(infoChar);

虽然您正在使用索引j重复课程
将线路改为

courses[j].setLetterGrade(infoChar);

应该解决你的问题

答案 1 :(得分:2)

您在最后一行代码中遇到问题:

courses[i].setLetterGrade(infoChar);

计数器为i而非j,因此更正为:

courses[j].setLetterGrade(infoChar);

希望它有所帮助!