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.
>`, so you don't need to know the size beforehand.
– Federico klez Culloca Jun 06 '21 at 16:29