-1

I am facing a problem with 2D arrays, and I don't know what is the problem or what does the error means too, I am trying to prompt the user to enter the number of classes, and for each class the number of students, and for each student, the name of each one of them in each class, and I have to append the names of students to a 2D array, but I just enter one student's name and it throws an error.

This is my code:

public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int classes = 0;
        int students = 0;
        int classNum;
        int student;

        System.out.print("Number of classes in the school: ");        // Prompt the user to enter the number of classes in the school
        classes = input.nextInt();

        String[][] studentNamesArr = new String[classes][students];
        for (classNum = 1; classNum <= classes; classNum++){
            System.out.printf("Enter number of Students in class number %d: ", classNum);
            students = input.nextInt();
            for (student = 1; student <= students; student++){
                System.out.printf("Enter Name for student %d in class number %d: ", student, classNum);
                studentNamesArr[classNum][student] = input.next();
            }
        }
    }

and this is the output when I run the code:

Number of classes in the school: 2
Enter number of Students in class number 1: 3
Enter (Name, study Type, Grade) for student 1 in class number 1: Joe

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds
for length 0 at StudentProgress.main(StudentProgress.java:28)

no idea how I can store the names properly in a 2D array.

Nibras Shami
  • 144
  • 2
  • 14
  • 2
    Changing the value for `students` doesn't retroactively change the size of `studentNamesArr`. You need to define it *after* you know the value for `students`. Also, those loops should stop at `< classes` and `< students`, not at `<= classes` and `<= students` – Federico klez Culloca Jun 06 '21 at 16:20
  • Even better, use a `List>`, so you don't need to know the size beforehand. – Federico klez Culloca Jun 06 '21 at 16:29
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – geocodezip Jun 06 '21 at 17:26

3 Answers3

2
  • The ArrayIndexOutOfBoundsException is thrown because you defined a 2d array of size [classesCount][0]. Since each class has a different size, we should initialize classes after the dynamic input was taken from the user.

  • The code iterates from index 1 and where the array starts from index 0.

  • Make sure to give meaningful names to the variable (students -> studentsNum/studentsCount and etc').

You can do as follows:

Scanner input = new Scanner(System.in);

System.out.print("Number of classes in the school: ");        // Prompt the user to enter the number of classes in the school
int classesCount = input.nextInt();

String[][] studentNamesArr = new String[classesCount][];
for (int classIndex = 0; classIndex < classesCount; classIndex++){
    System.out.printf("Enter number of Students in class number %d: ", classIndex+1);
    int studentsNum = input.nextInt();
    studentNamesArr[classIndex] = new String[studentsNum];
    for (int studentIndex = 0; studentIndex < studentsNum; studentIndex++){
        System.out.printf("Enter Name for student %d in class number %d: ", studentIndex+1, classIndex+1);
        studentNamesArr[classIndex][studentIndex] = input.next();
    }
}

System.out.println(Arrays.deepToString(studentNamesArr));

Output:

Number of classes in the school: 2
Enter number of Students in class number 1: 1
Enter Name for student 1 in class number 1: John
Enter number of Students in class number 2: 2
Enter Name for student 1 in class number 2: Wall
Enter Name for student 2 in class number 2: Simba
[[John], [Wall, Simba]]
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
1

You need to update your array at the class's index with a new array that can hold the students' names after you asked how many students there are in a class. Also arrays' indices begin at 0.
Here is the updated code:

public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int classes = 0;
        int students = 0;
        int classNum;
        int student;

        System.out.print("Number of classes in the school: "); // Prompt the user to enter the number of classes in the school
        classes = input.nextInt();

        String[][] studentNamesArr = new String[classes][students]; // At this point "students" is 0
        for (classNum = 1; classNum <= classes; classNum++){
            System.out.printf("Enter number of Students in class number %d: ", classNum);
            students = input.nextInt();
            studentNamesArr[classNum] = new String[students]; // Create the Array to store the names
            for (student = 0; student < students; student++){ // Indices start with 0
                System.out.printf("Enter Name for student %d in class number %d: ", student, classNum);
                studentNamesArr[classNum][student-1] = input.next();
            }
        }
    }
Quadslab
  • 294
  • 3
  • 9
1

The problem in your code is first you set students=0 and that means the length of the outer array is 0 then you again set students=some input number form keyboard but this doesn't affect the length of outer array of studentNamearr which is already 0.You can't achieve this by 2d array because number of students in one class can vary with another class but in 2d array number of elements in array must be equal.

Yaphet17
  • 123
  • 9