I have written a couple of functions which both give me the same error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
I don't understand what the problem is, I have searched the internet but I still don't understand it.
The code in question is this:
import java.util.Arrays;
public class examen2019 {
static int[] imagenEspejo(int[] arr){
int i;
int[] result = new int[arr.length*2];
for(i=0;i<=arr.length*2;i++){
if( i<=arr.length){
result[i]= arr[i];
}else{
result[i]= arr[i-arr.length];
}
}return result;
}
static boolean alMenosDos(int[] arr, int n){
int i;
int j = 0;
boolean result= false;
for(i=0;i<=arr.length;i++){
if (n== arr[i]){
j++;
}
if (j>= 2){
result= true;
}
}return result;
}
public static void main(String[] args){
int[] arr={1,2,4,5};
System.out.println(imagenEspejo(arr));
}
}
This error is raised to indicate that an array with an illegal index has been accessed. The index is negative or greater than or equal to the size of the array or array.
For example: you have an array of 4 elements and you try to access index 4, this will cause an error because the arrays start with index 0, so
For this reason, when you start a for loop and start counting from position 0, you must validate that it is less than the length of the array.
Your code just needs an adjustment to the loops.