Exception in the main when entering case 2 [closed]

0

It gives me exception error, eclipse tells me that it is the line that is marked (**) I have been trying for days and I do not get anything. Thanks

public static void main(String[] args) {
        boolean menu = true;
        System.out.println("¿Cuantos alumnos quiere?");
        int numAlumnos = Leer.entero();
        String alumnos [] = new String [numAlumnos];
        while(menu) {
        System.out.println("Introduzca una opción:");
        System.out.println("\t1. Introducir nombres");
        System.out.println("\t2. Notas del alumno");
        System.out.println("\t8. Exit");
        int opcion = Leer.entero();
        String[][] notas = new String[4][alumnos.length];
        switch (opcion) {
            case 1:
                System.out.println("******INTRODUZCA LOS NOMBRES*******");
                for(int i = 0;i<alumnos.length;i++) {
                    System.out.println("Indique el nombre del "+(i+1)+"º alumno");
                    alumnos[i] = Leer.texto();
                }
                break;

            case 2:
                System.out.println("******INTRODUZCA LAS NOTAS*******");
                for(int i = 0;i<alumnos.length;i++) {
                    for(int j = 1; j<4;j++) {
                        System.out.println("La nota de "+alumnos[i]+" del "
                                + (j)+"º Trimestre es: ");
                    **  notas[i][j] = Leer.texto();
                    }
                }
                break;
    
asked by dani luque castro 27.12.2018 в 18:23
source

1 answer

1

Exchange indexes: use notas[j][i] = ... , because according to the statement

String[][] notas = new String[4][alumnos.length];

You have an array of 4 elements, where each one has N students.

And it is j that is limited to be less than 4 e i which is limited to be less than N:

for(int i = 0;i<alumnos.length;i++) {
    for(int j = 1; j<4;j++) {
        ...
        notas[i][j] = Leer.texto(); // i sobrepasa 4 y te da un ArrayIndexOutOfBoundsException
    
answered by 28.12.2018 / 12:49
source