Issue
I was doing an exercise and in which you ask us the following: Exercise 06: Read the data corresponding to two tables of 12 numerical elements and mix them in a third of the form: 3 from tables A, 3 from B, others 3 of the A, another 3 of the B, Etc. When making the code (according to me it is fine) I get an error in netbeans (attached a photo) can you tell me what is the reason for my error? I'm still a student. In advance thank you very much for reading (I attach my code and the image of the error).
package ejercicioarreglos_06;
import java.util.Scanner;
public class EjercicioArreglos_06 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tablaA[] = new int[12];
int tablaB[] = new int[12];
int contador = 0;
boolean eleccion = true;
int contA = 0, contB = 0;
for (int i = 0; i < tablaA.length; i++) {
System.out.print("Ingresa el valor " + (i + 1) + " de la tabla A: ");
tablaA[i] = in.nextInt();
}
for (int j = 0; j < tablaB.length; j++) {
System.out.print("Ingrese el valor " + (j + 1) + " de la tabla B: ");
tablaB[j] = in.nextInt();
}
for (int k = 0; k < tablaB.length + tablaB.length; k++) {
if (eleccion = true) {
System.out.println(tablaA[contA]);
contador++;
contA++;
if (contador > 2) {
eleccion = false;
}
} else {
System.out.print(tablaB[contB]);
contador--;
contB++;
if (contador < 0) {
eleccion = true;
}
}
}
}
}
Solution
According to Javadoc:
ArrayIndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
ArrayIndexOutOfBoundsException
It is an exception (error) that happens when we provide an index outside the limits allowed for the access of elements in an array. Remember that Java indexes start at 0 and go up to the number of elements -1.
Note the position of the public class ArrayIndexOutOfBoundsException in the class hierarchy of the Java platform:
-> java.lang.Object
--> java.lang.Throwable
---> java.lang.Exception
----> java.lang.RuntimeException
-----> java.lang.IndexOutOfBoundsException
------> java.lang.ArrayIndexOutOfBoundsException
Here is an example where we try to access an element of an array using an invalid index:
public class Test{
public static void main(String args[]){
// an array of five elements
int[] values = {8, 98, 100, 3, 14};
// we will provide an invalid index
System.out.println(values[5]);
System.exit(0);
}
}
This code compiles normally. However, when we try to run it, we get the following error message:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at Study.main(Test.java:7)
The most appropriate way to correct this error is to provide an index value that is really in the allowed range.
Answered By - Echelon