Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

0

I am learning basic programming in Java and when I try to go through a array one-dimensional I get this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
        at Array_2.main(Array_2.java:6)

And I really do not know what I can do to solve it, this is the code:

public class Array_2 {
    public static void main(String args[]) {
        int t = 0;
        int numeros[] = new int[5];
        for (int i = 0; i <= 5; i++) {
            numeros[i] = i + 10;
        }
        for (int j = 0; j <= 5; j++) {
            System.out.println(numeros[t]);
            t++;
        }
    }
}
    
asked by jhonny 08.12.2018 в 01:31
source

2 answers

0

1st, which is not <= 5 if not < 5 .

2nd, in the second for you have already declared j , so for you to use t .

I leave the code:

public class Array_2{

    public static void main(String args[]){

        int numeros[] = new int[5];

        for(int i = 0; i < 5; i++) {
            numeros[i] = i + 10;
        }

        for(int j = 0; j < 5; j++) {
            System.out.println(numeros[j]);
        }
    }
}

If you perform a desktop test you will realize that when i is equal to 5, the condition of the for is fulfilled, so it enters to execute the body or block of the for, and when it comes to accessing the position 5 of the array will throw an exception indicating that this index ( i or j ) is outside the limits of the array.

And ... why this? Well why are you declaring an array of 5 positions, but you start counting from the zero position, and from zero to four are already the five positions.

    
answered by 08.12.2018 / 01:38
source
1

we must remember that the fixes start from the 0 index, so if you have one of size [5] since its first index is 0 and the last one is 4 , therefore it is not well declared your for , since you are telling it to end in the index 5 : (i<=5 ó j<=5) when it should be in 4 , in two ways:

i <= 4

or

i < 5

Greetings.

    
answered by 08.12.2018 в 01:50