处理“ ArrayIndexOutOfBoundsException”

时间:2018-10-06 09:15:50

标签: swing

我该如何处理? `

1 个答案:

答案 0 :(得分:0)

首先,在for循环之外创建标记[]。

第二,因为“课程”整数是动态的。最好不要首先初始化“标记”数组中的列数。

        Scanner s = new Scanner(System.in);

        int numberOfStudents = s.nextInt();

         String[] firsstNames = new String[numberOfStudents];
         String[] lastNames = new String[numberOfStudents];
         int[] studentID = new int[numberOfStudents];

        //will store marks for each student
        int[][] marks = new int[numberOfStudents][];

        for (int i = 0; i < numberOfStudents; i++) {
            System.out.println(i + "  " + "What is Student first name ? ");
            firsstNames[i] = s.next();
            System.out.println(i + "  " + "What is Student last name ? ");
            lastNames[i] = s.next();
            System.out.println(i + "  " + "What is Student ID ? ");
            studentID[i] = s.nextInt();
            System.out.println(i+1 + "  " + "how many courses ?  ");
            int courses = s.nextInt();
            marks[i] = new int[courses];


            for (int j = 0; j < courses; j++) {
                System.out.println("enter the marks : ");
                int input = s.nextInt();
                marks[i][j] = input;
            }
        }

        for(int i=0;i<numberOfStudents;i++){
            for(int j=0;j<marks[i].length;j++){
                System.out.print(marks[i][j] + " ");
            }
            System.out.println();
        }
       s.close();