Error java.lang.ArrayIndexOutOfBoundsException in java

1

I have an error in a very basic java exercise. I have not touched this language for a long time, and I do not know what is happening ... (I'm sorry if it's silly, but I do not see it, really).

I have a vector, of 100 positions, which I fill in an ascending way and then, I do a function to add the positions and show it on the screen. I have to use the function, because the exercise is longer, but I have the problem here, on line 22.

public class Main {

public static void main(String[] args) throws IOException {
    //Esto es para un switch case
    System.out.println("Que opcion quieres.\n1Ejecutar por consola.\n2Ejecutar por dialogo.\n3Salir");
    InputStreamReader flujo = new InputStreamReader(System.in);
    BufferedReader teclado = new BufferedReader(flujo);
    String opcion = teclado.readLine();
    //Creo el array de 100 posiciones
    int[] cienNumeros = new int[100];
    //Numeros es desde donde va a empezar, la posicion 0
    int numeros = 1;

    for (int i = 0; i <= cienNumeros.length; i++) {
        //*************AQUI ME DA EL ERROR EN LA CONSOLA, NO LO ENTIENDO
        cienNumeros[i] = numeros;
        numeros++;
        System.out.println(cienNumeros[i]);
    }

    int total = 0;
    total = suma(cienNumeros);
    System.out.println(total);
}

// Metodos
public static int suma(int[] cienNumeros) {
    int suma = 0;
    for (int h = 0; h <= cienNumeros.length; h++) {
        suma += cienNumeros[h];
    }
    return suma;
}

}

Thank you very much everyone, I know it will be silly, but I do not see the error.

    
asked by cupax64 08.12.2018 в 21:49
source

1 answer

1

The length of the array is 100 but the positions always start at 0, that is they go from 0 to 99.

Then when i is 100 your condition i <= cienNumeros.length is fulfilled but does not exist such position and when you try to execute hundredNumbers [100] the error jumps to you.

Try this:

 for (int i = 0; i < cienNumeros.length; i++) {
        cienNumeros[i] = numeros;
        numeros++;
        System.out.println(cienNumeros[i]);
    }
    
answered by 08.12.2018 / 21:55
source