Hi, I'm trying to put two arrays inside one and I get the following error;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20
I'm new to programming in java given that I've been looking at many places but the truth is that I can't find a solution in case someone could help. Below is the code. // Let's say the problem would start from "Exercise 3".
public static void main(String args[]) {
/*Crea un programa con dos arrays de tamaño 20 y otro de tamaño 40
El primer array lo llenaremos con numeros aleatorios entre el 0 y el 20
el segundo array será la copia inversa del primer array
el terter array está formado por los dos primeros que sería la primera mitad del
array 1 y la segunda mitad el array2*/
int array1[] = new int[20];
int array2[] = new int[20];
int array3[] = new int [(20+20)-1];
int array4[] = new int[40];
for (int i = 0; i < array1.length; i++) {
int valorAleatorio = (int)(Math.random() * (20+1));
array1[i] = valorAleatorio;
}
System.out.println("");
System.out.println("*************************");
System.out.println("Ejercicio 1");
System.out.println("*************************");
System.out.println("");
for (int i = 0 ; i < array1.length; i++) {
System.out.println("Array[" + i + "] = " + array1[i]);
}
System.out.println("");
System.out.println("*************************");
System.out.println("Ejercicio 2");
System.out.println("*************************");
System.out.println("");
int j=array2.length-1;
for(int i=0;i<array1.length;i++){
array2[i] = array1[j];
System.out.println("Array2[" + i + "] = " + array2[i] + " <-- Array1[" + (j) + "] = " + array1[j]);
j--;
}
System.out.println("");
System.out.println("*************************");
System.out.println("Ejercicio 3");
System.out.println("*************************");
System.out.println("");
for(int i = 0; i < array3.length; i++){
array3[i] = array1[i] + array2[i];
System.out.println("Array3[" + i + "] = " + array3[i] + " <-- Array1[" +i+ "] = " + array1[i]);
System.out.println("Array3[" + (i) + "] = " + array3[(i)] + " <-- Array2[" +i+ "] = " + array2[i]);
}
}
The problem with the error that you get is that you are trying to access elements of array1 and array2 that do not exist. You do this when doing the for, taking as reference the size of array3 (39) and you try to obtain values from array1 and array2 that have size (20)
(EDITED) Once I have seen your clarification, I have modified the code so that it is as you say: And by the way, when declaring the size of the array3, it is better to do it like this:
int array3[] = new int [array1.length + array2.length];
This way you save problems with the size. Because another problem that you were going to have if you put onlyint array3[] = new int [39];
was that you were not going to be able to access array3[39], that you need it if you want to put the 40 elements of array1 and array2, this is because the array starts counting from 0 to 39 -1 and you would get the same error again.